All Revision Notes

COM6005 Statistical Modeling · Module 1

Descriptive Statistics & Inferential Statistics

COM6005 · Module 1 · Source: Module_1_Introduction_2026.pdf (26 slides)

Contents · 9 sections

🎯 本講重點 (Learning outcomes)

  • 分清 Descriptive statistics(描述手上數據)同 Inferential statistics(由 sample 推論 population)。
  • 識講 location parameter(mean / median / mode / sum)同 dispersion parameter(SD / variance / range / IQR / percentile),並識計。
  • 知道 inferential statistics 包括 population vs sample、Confidence Interval、Hypothesis testing、p-value、prediction models。
  • 分辨兩類模型:prediction of numeric value(→ Linear regression)同 Classification(→ Logistic regression)。
  • 理解 training data / new data、n(rows)同 p(columns of X),classical(p 細 n 大)vs modern(p、n 都可以大)情況。
  • 識用 naïve 方法:畫直線做 prediction;用 k-nearest neighbor + Euclidean distance 做 classification。

⭐ 考試必溫 Top-5

  1. Descriptive vs Inferential 嘅定義同例子(HSUHK 畢業生薪金 = sample;香港勞動市場薪金 = population)。
  2. Location vs Dispersion measures 嘅分類,同埋 mean / median / variance / SD / range / IQR 嘅計算。
  3. 判斷一個問題係 numeric prediction 定 classification,並講出 n 同 p(例如 digit recognition:n=60,000n = 60{,}000、p=784p = 784)。
  4. k-NN 嘅 4 個步驟 + Euclidean distance 公式,並識手計一個例子。
  5. Linear regression ↔ numeric prediction;Logistic regression ↔ classification。

1. Descriptive vs Inferential Statistics

統計學可以粗略分兩大類(slide 2):

⭐ 考試重點:定義(slide 2)
  • Descriptive Statistics: gain an overview of the distribution of data sets. Aim to summarize and present observed data using numerical measures, charts, and tables.
  • Inferential Statistics: use sample data to estimate characteristics of a population or test claims about that population.

一句講晒:Descriptive 只係「描述你手上見到嘅數據」;Inferential 係「用 sample 去估計/檢驗你見唔晒嘅 population」。

Slide 3 嘅例子:

例子適用
Sample dataSalaries of HSUHK graduates計 sample mean、畫 histogram → Descriptive
PopulationSalaries in Hong Kong labour market用 HSUHK sample 推論全港薪金 → Inferential
💡 直覺理解

如果你話「我問咗 200 個 HSUHK 畢業生,平均月薪係 $22,000」——呢句係 descriptive(純粹總結 sample)。如果你再講「所以我有 95% 信心全港大學畢業生平均月薪喺 $21,000–$23,000 之間」——呢句已經係 inferential,因為你由 sample 跳去 population,必然帶有不確定性(uncertainty),所以要用 Confidence Interval / Hypothesis testing 去量化。

🖼️ 圖片內容

Slide 3 有一張 descriptive vs inferential 嘅示意圖(來源 numiqo.com),圖片內容文字擷取不到;請對照原 slide 第 3 頁。

2. Descriptive Statistics:Location 同 Dispersion

Slide 4 將 descriptive statistics 分做四大類:

類別包括回答咩問題?
Location parameter / characteristicMean (Average)、Median、Mode、Sum數據「中心」喺邊?
Dispersion parameter / characteristicStandard deviation、Variance、Range、IQR (Interquartile range)、Percentile數據有幾「散」?
Tablesfrequency table、contingency table用表格總結
Chartshistogram、boxplot、bar chart、scatter plot用圖總結

2.1 公式

xˉ=1n∑i=1nxis2=1n−1∑i=1n(xi−xˉ)2s=s2\bar{x} = \frac{1}{n}\sum_{i=1}^{n} x_i \qquad s^2 = \frac{1}{n-1}\sum_{i=1}^{n}(x_i-\bar{x})^2 \qquad s=\sqrt{s^2}
Range=xmax⁡−xmin⁡IQR=Q3−Q1  (75th percentile−25th percentile)\text{Range} = x_{\max}-x_{\min} \qquad \text{IQR} = Q_3 - Q_1 \;(\text{75th percentile} - \text{25th percentile})
  • Median:排好序之後中間嗰個(n 雙數就取中間兩個嘅平均)。
  • Mode:出現次數最多嘅值(categorical data 都用得)。
  • Percentile:第 k 個 percentile 即係有 k% 數據 ≤ 呢個值;Q1Q_1 = 25th、Median = 50th、Q3Q_3 = 75th percentile。

2.2 Worked example(用 slide 15 嘅 Sales 數據)

Y=SalesY = \text{Sales}:60, 43, 52, 36, 40(n=5n = 5)

⭐ 手計步驟
  1. 排序:36, 40, 43, 52, 60
  2. Mean:yˉ=(60+43+52+36+40)/5=231/5=46.2\bar{y} = (60+43+52+36+40)/5 = 231/5 = 46.2
  3. Median:第 3 個 = 43(mean > median → 有少少 right-skewed)
  4. Mode:冇重複值 → 冇 mode
  5. Sum:231
  6. Range:60 − 36 = 24
  7. Variance:偏差平方 (13.8)2+(−3.2)2+(5.8)2+(−10.2)2+(−6.2)2=190.44+10.24+33.64+104.04+38.44=376.8(13.8)^2+(-3.2)^2+(5.8)^2+(-10.2)^2+(-6.2)^2 = 190.44+10.24+33.64+104.04+38.44 = 376.8;s2=376.8/(5−1)=94.2s^2 = 376.8/(5-1) = 94.2
  8. SD:s=94.2≈9.71s = \sqrt{94.2} \approx 9.71
  9. IQR(numpy 預設 linear interpolation):Q1=40Q_1 = 40、Q3=52Q_3 = 52 → IQR=IQR = 12
⚠️ 常見錯誤
  • Sample variance 除 n−1n - 1(唔係 n)。pandas .var() 預設 ddof=1;numpy np.var() 預設 ddof=0,要寫 np.var(y, ddof=1)。Module 3a 計 t-statistic 時 slide 都特登寫 y.var(ddof=1)。
  • Quartile 有幾種計法(不同教科書/軟件答案可能差少少),考試跟題目指定方法。
  • Mean 受 outlier 影響大;median、IQR 比較 robust。
import pandas as pd
import numpy as np
y = pd.Series([60, 43, 52, 36, 40])
print(y.mean(), y.median(), y.sum())          # 46.2 43.0 231
print(y.var(), y.std())                        # 94.2 9.705...(ddof=1)
print(y.max() - y.min())                       # Range = 24
print(y.quantile(0.75) - y.quantile(0.25))     # IQR = 12.0
print(y.describe())                            # 一次過出 count/mean/std/min/25%/50%/75%/max

3. Inferential Statistics 包括咩?

Slide 5 列出 inferential statistics 嘅主要內容(之後幾個 Module 會逐一詳細講):

⭐ 考試重點(slide 5)
  • Population vs Sample:A population is the entire group of people or things you want to study, while a Sample is a smaller, manageable subset chosen from that population.
  • Confidence Intervals:Giving a range of plausible values rather than just a single guess, showing how sure you are.(→ Module 3)
  • Hypothesis Testing:Testing an idea or claim about a population to see if the sample data supports it or shows it is false.(→ Module 3, 3a, 3b)
  • P-values:Measuring the probability that your results happened just by random luck rather than a real effect.(→ Module 3)
  • Prediction models, etc.(→ Module 4 Linear regression)
⚠️ 易混淆

Slide 5 對 p-value 嘅描述係簡化版。Module 3 會俾正式定義:p-value 係「假設 H0H_0 成立之下,得到等於或更極端結果嘅(conditional)probability」,唔係「H0H_0 為真嘅機率」。

4. 兩類模型:Prediction vs Classification

Slide 6:課程會研究兩類模型——

類型Y 係咩例子常用方法
Prediction of numeric valuenumerical / continuousprice、sales、fuel consumptionLinear regression
Classificationcategorical(類別)cancer/healthy、agree/neutral/disagree、phase I/II/III cancerLogistic regression
⭐ 考試重點

判斷題型嘅關鍵係睇 Y 嘅 data type:Y 係數字(連續)→ numeric prediction(regression);Y 係類別 → classification。X 係咩 type 唔影響呢個判斷。

4.1 Background:Training data、n 同 p(slide 7)

  • Problem:In the training data, both X and Y are given. In the new data, only X is known. The goal is to guess Y for the new data.
  • Multivariate means p is more than 1. n = number of rows in training;p = number of columns in X。
  • Classical situation:p is small, n is large。
  • Modern situation:both p and n can be large。
  • PCA 同 LASSO 係處理 modern large-p 問題嘅技術。
💡 直覺理解

當 p 大過 n(例如 6000 個 gene、得 50 個病人),你嘅「未知數」多過「方程」,普通 regression 解唔到唯一答案,亦極易 overfitting。PCA 將 p 個變數壓縮成少數 principal components;LASSO 加 penalty 令大部分 coefficient 變 0,自動揀變數。

4.2 四個例子(slides 8–13)

例子XY題型n, p
Fuel consumption(slide 8)X1X_1 %Driving License, X2X_2 Income, X3X_3 TaxFuel consumption(數字)Numeric predictionn=4n = 4(training 年份 2016–2019), p=3p = 3
Heart attack(slide 9)X1X_1 Tobacco, X2X_2 Family history (Present/Absent), X3X_3 AlcoholGet heart attack? Yes/NoClassificationn=4,p=3n = 4, p = 3
Handwritten digit(slides 10–11)28×28=78428 \times 28 = 784 個 pixel(Black/White)digit 0–9Classification(10 類)n=60,000,p=784n = 60{,}000, p = 784(n、p 都大 → modern)
Cancer microarray(slides 12–13)6000 個 gene expression levelHealthy / CancerClassificationn=50,p=6000n = 50, p = 6000(p≫np \gg n → modern large-p)
⭐ Slide 10、12 嘅問題 “Type of this problem???”

Digit recognition:Y 係 0–9 嘅類別 → classification(雖然 Y 寫成數字,但「3」同「4」之間冇大小意義,只係 label)。Microarray:Y 係 Healthy/Cancer → classification,而且係 p (6000) 遠大過 n (50) 嘅 modern situation,要用 PCA / LASSO 類方法。

⚠️ 常見錯誤

見到 Y 係數字就以為係 regression——digit 0–9 係 categorical label。同樣,X 入面有 categorical(Family history)都唔會令題目變成 classification;決定題型嘅只係 Y。

🖼️ 圖片內容

Slides 10、12 右邊有 handwritten digit 同 microarray 嘅示意圖,文字擷取不到;請對照原 slide。

5. Prediction:Is it possible?(p = 1 簡單情況)

Slide 15 嘅數據:X=Advertisement ExpenditureX = \text{Advertisement Expenditure},Y=SalesY = \text{Sales}。

YearXY
201517260
201615643
201716752
201814536
201915040
2025 (new)180???

Naïve method for prediction p=1p = 1(slide 16):

  1. Plot the training data(scatter plot)
  2. Draw a straight line that “fit the data well”
  3. Make prediction from the straight line

Slide 17 嘅圖顯示:5 個 training 點大致排成一條直線,喺 X=180X = 180 嗰度沿直線讀出 Y≈65Y \approx 65。

💡 預告 Module 4:用 OLS 正式計條線

「fit the data well」嘅正式定義係 Ordinary Least Squares:揀 a、b 令 ∑(Yt−a−bXt)2\sum (Y_t - a - bX_t)^2 最細。答案:

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

代入:Xˉ=158, Yˉ=46.2, SXX=514, SXY=434\bar X = 158,\ \bar Y = 46.2,\ S_{XX} = 514,\ S_{XY} = 434 → b^=434/514≈0.8444\hat b = 434/514 \approx 0.8444,a^=46.2−0.8444(158)≈−87.21\hat a = 46.2 - 0.8444(158) \approx -87.21。
Prediction:Y^=−87.21+0.8444(180)≈64.8\hat Y = -87.21 + 0.8444(180) \approx 64.8,同 slide 17 圖上讀到嘅 ≈65\approx 65 吻合。

6. Classification:Is it possible?(p = 2,k-NN)

Slide 19 用 Iris 數據:X1=Sepal LengthX_1 = \text{Sepal Length}、X2=Sepal WidthX_2 = \text{Sepal Width}、Y=SpeciesY = \text{Species}(Setosa / Versicolor / Virginica)。New data = (5.3, 3.3)。

Naïve method for classification p=2p = 2(slide 20):

  • Plot the training data with labels
  • For the new data, check the neighboring training data. “Neighbor” requires the concept of distance.
  • Predict based on the proportions of neighboring points falling into different categories

Slide 21 嘅 scatter plot:新點(紅色菱形,約 (5.3, 3.25))周圍畫咗一個圓圈 “Neighbor of new data”,圈入面大部分係 setosa(圓圈符號)。

⭐ k-nearest neighbor method(slide 22)
  1. Compute the distances (Euclidean) between the new point to all training points.
  2. Consider k training points that are the closest to the new point.
  3. Count the proportion of each category.
  4. Predict the category with the largest proportion.

Slide 例子:k=5k = 5 → P(setosa)=5/5P(\text{setosa}) = 5/5、P(versicolor)=0/5P(\text{versicolor}) = 0/5、P(virginica)=0/5P(\text{virginica}) = 0/5 → predicted as “setosa”。

Euclidean distance(slide 23)between (x1,y1)(x_1,y_1) and (x2,y2)(x_2,y_2):

d=(x1−x2)2+(y1−y2)2d = \sqrt{(x_1-x_2)^2 + (y_1-y_2)^2}

6.1 Worked example:用 slide 19 列出嘅 4 個 training 點

New point = (5.3, 3.3)

Training pointSpeciesDistance
(5.1, 3.5)Setosa0.22+0.22=0.08≈0.283\sqrt{0.2^2+0.2^2} = \sqrt{0.08} \approx 0.283
(4.9, 3.0)Setosa0.42+0.32=0.25=0.500\sqrt{0.4^2+0.3^2} = \sqrt{0.25} = 0.500
(5.9, 3.0)Virginica0.62+0.32=0.45≈0.671\sqrt{0.6^2+0.3^2} = \sqrt{0.45} \approx 0.671
(6.2, 3.4)Virginica0.92+0.12=0.82≈0.906\sqrt{0.9^2+0.1^2} = \sqrt{0.82} \approx 0.906

如果 k=3k = 3(淨係用呢 4 點示範):最近 3 個 = Setosa, Setosa, Virginica → P(setosa)=2/3P(\text{setosa}) = 2/3、P(virginica)=1/3P(\text{virginica}) = 1/3 → predict Setosa。

import numpy as np
from collections import Counter
train_X = np.array([[5.1, 3.5], [4.9, 3.0], [6.2, 3.4], [5.9, 3.0]])
train_y = np.array(["Setosa", "Setosa", "Virginica", "Virginica"])
new = np.array([5.3, 3.3])
d = np.sqrt(((train_X - new) ** 2).sum(axis=1))   # Euclidean distance
k = 3
nearest = train_y[np.argsort(d)[:k]]               # 最近 k 個嘅 label
print(d.round(3), Counter(nearest))                # Setosa: 2, Virginica: 1

# 用 scikit-learn
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=3).fit(train_X, train_y)
print(knn.predict([new]), knn.predict_proba([new]))
⚠️ 常見錯誤
  • k 太細(例如 1)→ 對 noise 好敏感;k 太大 → 鄰居包含太多遠嘅點,界線變模糊。k 通常揀單數避免打和。
  • Euclidean distance 受 scale 影響:如果一個變數單位係「千」、另一個係「0.1」,大 scale 嗰個會主導 distance,所以實務上要先 Normalization / Standardization。
  • Slide 23 話 “You can learn better definitions if you study more statistics”——即係仲有 Manhattan、Mahalanobis 等其他 distance。
🖼️ 圖片內容

Slides 14、18 只有標題頁/圖片(“Prediction: Is it possible?”、“Classification: Is it possible?”),冇額外文字。

7. 其他相關數學知識同 Python

Slide 24 列出之後會用到嘅數學:

範疇內容用喺邊
Linear algebraMatrix、solving linear equations、matrix inverseRegression(Module 4:β^=(X′X)−1X′Y\hat\beta = (X'X)^{-1}X'Y)
Linear algebraEigenvalue and eigenvectorPrincipal component analysis (PCA)
CalculusDerivatives、maximum、minimumOLS:對 SS 求導 = 0 搵最小值

Problem Solving with Python(slides 25–26):大部分統計方法都可以用 Python(freeware)做。Python tutorial 會示範:

  • Reading data to the computer(例如 pd.read_csv())
  • Specifying the data type (numerical, categorical)(例如 astype("category"))
  • Drawing graphs visualizing the data(matplotlib / seaborn)
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({"adv": [172, 156, 167, 145, 150],
                   "sales": [60, 43, 52, 36, 40]})
df["year"] = pd.Categorical([2015, 2016, 2017, 2018, 2019])  # 指定為 categorical
print(df.dtypes)
plt.scatter(df["adv"], df["sales"])      # 畫 scatter plot 睇下係咪似直線
plt.xlabel("Advertisement"); plt.ylabel("Sales"); plt.show()

自我測驗 Self-test

Q1. 「調查 300 個香港中學生每日用手機時間,平均 4.2 小時」同「由此推斷全港中學生平均用手機時間嘅 95% CI 係 (3.9, 4.5)」各屬咩類統計?

前者係 Descriptive(總結 sample);後者係 Inferential(由 sample 推論 population,用 Confidence Interval)。Sample = 300 個學生;Population = 全港中學生。

Q2. 數據 3, 7, 7, 10, 13:計 mean、median、mode、range、sample variance、SD。

Mean = 40/5 = 8;Median = 7;Mode = 7;Range = 13 − 3 = 10。偏差平方:25 + 1 + 1 + 4 + 25 = 56;s2=56/4=14s^2 = 56/4 = 14;s=14≈3.742s = \sqrt{14} \approx 3.742。

Q3. 將以下歸類為 location 或 dispersion:median、IQR、sum、percentile、mode、variance。

Location:median、sum、mode。Dispersion:IQR、percentile、variance(跟 slide 4 嘅分類,percentile 列喺 dispersion 之下)。

Q4. 用病人嘅年齡、血壓、膽固醇預測「住院日數」,同預測「會否再入院 (Yes/No)」,各屬咩題型?建議用咩方法?

住院日數係數字 → numeric prediction → Linear regression。再入院 Yes/No 係類別 → Classification → Logistic regression。兩題都係 p=3p = 3。

Q5. Handwritten digit 數據:n 同 p 係幾多?屬 classical 定 modern situation?

n=60,000n = 60{,}000(training images),p=28×28=784p = 28 \times 28 = 784(pixels)。n 同 p 都大 → modern situation。題型係 classification(Y = 0–9 label)。

Q6. 新點 (2, 2);training 點 A(1, 1) 屬 “Red”、B(4, 2) 屬 “Blue”、C(2, 4) 屬 “Blue”、D(3, 3) 屬 “Red”、E(0, 2) 屬 “Blue”。用 k=3k = 3 嘅 k-NN 預測。

Distance:A=2≈1.414A = \sqrt{2} \approx 1.414;B=2B = 2;C=2C = 2;D=2≈1.414D = \sqrt{2} \approx 1.414;E=2E = 2。最近 3 個:A (Red)、D (Red),第三近有 B、C、E 打和(都係 2,而且全部係 Blue)→ 揀邊個都係 Blue。比例 Red 2/3、Blue 1/3 → predict Red。

Q7. 點解 microarray(n=50,p=6000n = 50, p = 6000)唔可以直接用普通 multiple linear regression?slide 提咗咩技術?

p≫np \gg n,參數多過觀測值,X′XX'X 唔可逆,有無限多組解,亦會嚴重 overfitting。Slide 7 提到 PCA(降維)同 LASSO(variable selection / shrinkage)用嚟處理 modern large-p 問題。Module 4 亦提到 multiple regression 要求 p 相對 n 細(p>10p > 10 已可能好有問題)。

Q8. Slide 15 數據用 OLS 計出 Y^=−87.21+0.8444X\hat Y = -87.21 + 0.8444X。廣告開支 = 160 時預測 sales?slope 點解讀?

Y^=−87.21+0.8444×160≈47.9\hat Y = -87.21 + 0.8444 \times 160 \approx 47.9。Slope:廣告開支每增加 1 單位,預期 sales 平均增加約 0.844 單位。

一頁總結 Cheat sheet

⭐ 考前速記
  • Descriptive = summarize observed data (numbers, charts, tables);Inferential = sample → population(estimate / test claims)。
  • Location:mean, median, mode, sum|Dispersion:SD, variance, range, IQR, percentile。
  • s2=∑(xi−xˉ)2n−1s^2 = \frac{\sum(x_i-\bar x)^2}{n-1};Range=max⁡−min⁡\text{Range} = \max - \min;IQR=Q3−Q1IQR = Q_3 - Q_1。
  • Inferential 包括:population vs sample、CI、Hypothesis testing、p-value、prediction models。
  • Y 數字 → numeric prediction(Linear regression);Y 類別 → Classification(Logistic regression)。
  • n = rows;p = columns of X;multivariate = p>1p > 1;classical:p 細 n 大;modern:p、n 都可以大 → PCA、LASSO。
  • Naïve prediction:plot → draw line → predict。
  • k-NN:計 Euclidean distance → 揀最近 k 個 → 計各類比例 → 揀最大。d=(x1−x2)2+(y1−y2)2d=\sqrt{(x_1-x_2)^2+(y_1-y_2)^2}。
  • 數學工具:matrix inverse(regression)、eigenvalue/eigenvector(PCA)、derivatives(optimisation)。