COM6004 Data Mining · Chapter 2
Data: Attributes, Quality, Similarity & Preprocessing
COM6004 · Chapter 2 · Source: COM6004_Chapter_2_Data.pptx (82 slides) · Sections 2.1 Data Quality, 2.2 Measures of Similarity and Dissimilarity, 2.3 Data Preprocessing
Contents · 13 sections
🎯 本講重點 (Learning outcomes)
- 分辨 attribute 四種類型(Nominal / Ordinal / Interval / Ratio)同佢哋擁有嘅 properties;分辨 Discrete vs Continuous。
- 認識各種 data set 類型(Record、Data Matrix、Document、Transaction、Graph、Ordered)。
- 理解 Data Quality 問題:Noise、Outliers、Missing Values(MCAR / MAR / MNAR)、Duplicate Data。
- 識計 Euclidean / Minkowski(、、)distance、SMC、Jaccard、Cosine similarity、Entropy、Mutual Information、combined similarity。
- 理解 distance 嘅 metric properties 同 Mahalanobis distance 嘅用途。
- 掌握 Data Preprocessing:Aggregation、Sampling、Dimensionality Reduction(curse of dimensionality、PCA)、Feature Subset Selection、Discretization、Binarization、Attribute Transformation / Normalization。
⭐ 考試必溫 Top-5
- NOIR 四種 attribute types 同 properties(distinctness、order、differences、ratios),例如點解 Celsius 係 interval、Kelvin 係 ratio。
- SMC vs Jaccard 計算(slide 44 例子:、)同幾時用邊個。
- Cosine similarity 計算(slide 45:)同 Minkowski distance()。
- Entropy 同 Mutual Information 嘅計算同解讀。
- Missing value 三種機制 MCAR / MAR / MNAR;Discretization(equal width / equal frequency / K-means / supervised)。
1. What is Data? Objects & Attributes
Slide 4:Dataset is a collection of data objects and their attributes.
- Attribute:object 嘅 property 或 characteristic(例如人嘅 eye color、temperature)。別名:variable、field、characteristic、dimension、feature。
- 一組 attributes 描述一個 Object。別名:record、point、case、observation、sample、entity、instance。
用表格諗:每一行係一個 object,每一欄係一個 attribute。
COM6001 pandas 嘅 DataFrame:row = object(index),column = attribute(feature);COM6002 RDBMS 入面 row = tuple / record,column = attribute / field。名稱唔同,概念一樣。
1.1 Attribute Values (Slide 5)
Attribute values 係分配俾某 object 嘅某 attribute 嘅數字或符號。要分清 attribute 同 attribute values:
- 同一個 attribute 可以 map 去唔同 values:例如 height 可以用 feet 或 meters 量度。
- 唔同 attributes 可以 map 去同一組 values:例如 ID 同 age 都係 integers。
- 但 values 嘅 properties 可以唔同:ID 冇上限,age 有最大同最小值;計 ID 嘅平均冇意義,計 age 平均就有。
2. Types of Attributes (NOIR)
ExamSlide 6–7 將 attributes 分四類,視乎佢擁有邊啲 properties / operations:
- Distinctness:
- Order:
- Differences are meaningful:
- Ratios are meaningful:
| Type | Properties | Slide 例子 | 有意義嘅統計 / 操作 |
|---|---|---|---|
| Nominal | distinctness | ID numbers、eye color、zip codes | mode、entropy、contingency / test |
| Ordinal | distinctness & order | rankings(薯片味道 1–10 分)、grades、height {tall, medium, short} | median、percentiles、rank correlation |
| Interval | distinctness, order & meaningful differences | calendar dates、temperatures in Celsius 或 Fahrenheit | mean、standard deviation、Pearson correlation、t-test |
| Ratio | all 4 properties | temperature in Kelvin、length、counts、elapsed time(跑步時間) | geometric mean、harmonic mean、percent variation |
Nominal + Ordinal = Categorical (Qualitative);Interval + Ratio = Numeric (Quantitative)。
Slide 9 係一個圖片表格(教科書嘅 attribute type 總表,列出 description / examples / operations),文字擷取不到;上表「有意義嘅統計」一欄係根據教科書標準內容補充,請對照原 slide 第 9 頁。
2.1 Ratio vs Interval (Slide 8)
Slide 問:「10° 係咪 5° 嘅兩倍熱?」
- Celsius / Fahrenheit:唔係!因為 0°C 唔係「冇溫度」,零點係人為設定。10°C = 283.15K,5°C = 278.15K,比例只係 1.018。所以 Celsius 只係 interval:差(10 − 5 = 5 度)有意義,比例冇意義。
- Kelvin:0K 係絕對零度(真正嘅「冇」),所以 10K 真係 5K 嘅兩倍 → ratio。
- Height above average:Bill 高過平均 3 inches,Bob 高過平均 6 inches,Bob 係咪「兩倍高」過 Bill?唔係——零點係「平均身高」而唔係「0 高度」,同 Celsius 情況一樣,屬 interval。
判斷 ratio 嘅方法:問自己「0 係咪代表完全冇呢樣嘢?」0 kg = 冇重量 → ratio;0 秒 = 冇時間流逝 → ratio;0°C ≠ 冇熱量 → interval;年份 0 年 ≠ 冇時間 → calendar dates 係 interval。
2.2 Discrete vs Continuous (Slide 10)
| Discrete Attribute | Continuous Attribute | |
|---|---|---|
| 定義 | Has only a finite or countably infinite set of values | Has real numbers as attribute values |
| 例子 | zip codes、counts、一批文件入面嘅 words | temperature、height、weight |
| 表示方式 | 通常用 integer variables | 通常用 floating-point variables |
| 備註 | Binary attributes 係 discrete 嘅特例 | 實際上只能用有限位數量度同表示 |
Discrete/Continuous(值嘅數量)同 NOIR(值嘅 properties)係兩個獨立維度。例如 zip code 係 discrete + nominal;counts 係 discrete + ratio;temperature (°C) 係 continuous + interval。唔好以為「discrete = categorical」。
2.3 Key Messages for Attribute Types (Slide 11)
- 你選擇嘅 operations 要對你嘅 data type 係 "meaningful"。
- Distinctness、order、meaningful intervals、meaningful ratios 只係 data 嘅四種 properties。
- 你見到嘅 data type(通常係數字或字串)未必反映晒所有 properties,甚至可能暗示唔存在嘅 properties(例如 zip code 係數字,但計平均冇意義)。
- 分析可能依賴其他 properties,例如好多統計分析只依賴 distribution。
- 有時 meaningful 由 statistical significance 衡量,但最終由 domain 決定。
3. Characteristics & Types of Data Sets
3.1 Important Characteristics of Data (Slide 12)
- Dimensionality(attributes 數目):高維 data 帶來好多挑戰(見 §10 curse of dimensionality)。
- Sparsity:只有「出現」先算數(only presence counts),例如 transaction data 大部分 items 都係 0。
- Resolution:patterns 取決於 scale(例如以「日」睇天氣同以「年」睇氣候見到嘅 pattern 唔同)。
- Size:分析類型可能取決於 data 大小。
3.2 Types of Data Sets (Slides 13–23)
| 類型 | 子類 / 說明 |
|---|---|
| Record Data | 由 records 組成,每個 record 有固定一組 attributes(slide 14)。
|
| Graph Data | Generic graph、molecular structures(例如 Benzene Molecule C6H6)、World Wide Web(網頁 + hyperlinks)(slide 19)。 |
| Ordered Data | Sequences of transactions(slide 21:items / events,每個 element 係 sequence 嘅一部分)、Genomic sequence data(slide 22:DNA 序列)、Spatio-Temporal Data(slide 23:陸地同海洋嘅每月平均溫度);另有 Spatial、Temporal、Sequential data。 |
Slides 14–17、19、21–23 嘅例子表格(例如 Tid/Refund/Marital Status 表、document-term matrix、transaction 表、graph 圖、基因序列、溫度地圖)均為圖片,未能擷取;請對照原 slide。
4. Data Quality (Section 2.1)
Slide 24:Poor data quality negatively affects many data processing efforts. Thomas C. Redman (2004) 估計差劣 data quality 令一般公司損失至少 10%(更可能係 20%)revenue。
Data Mining 例子:用差劣 data 建一個偵測 loan risk 嘅 classification model,結果:
- 一啲 credit-worthy 嘅申請人被拒絕貸款(誤判為高風險)
- 更多貸款批俾會 default 嘅人
Slide 25 提出三個問題:有咩 data quality 問題?點偵測?點處理?問題例子:Noise and outliers、Missing values、Duplicate data、Wrong data、Fake data。
4.1 Noise (Slide 26)
- 對 objects:noise 係一個外來 (extraneous) 嘅 object。
- 對 attributes:noise 指原本數值被修改 (modification of original values)。
- 例子:電話線差時聲音失真、電視雪花 ("snow")。
- Slide 圖:兩條不同頻率嘅 sine waves、合併後嘅波、再加 random noise → 原 signal 嘅 magnitude 同 shape 被扭曲。
4.2 Outliers (Slide 27)
Outliers are data objects with characteristics that are considerably different than most of the other data objects in the data set.
- Case 1:Outliers 係 noise,干擾分析 → 要處理 / 移除。
- Case 2:Outliers 正正係分析目標 → 例如 credit card fraud、intrusion detection(Anomaly Detection)。
Noise 係隨機誤差(量度錯誤),通常冇意義;Outlier 係真實但罕見嘅 object,可能非常有意義(例如一筆盜用信用卡交易)。Noise 唔一定係 outlier,outlier 亦唔一定係 noise。
4.3 Missing Values (Slides 28–29)
原因:(1) 資料冇收集到(例如人哋拒絕提供年齡同體重);(2) Attribute 唔適用於所有 cases(例如小朋友冇 annual income)。
處理方法:
- Eliminate data objects 或 variables(刪 row / 刪 column)
- Estimate missing values(例如 time series of temperature 用前後值估;census results)
- Ignore the missing value during analysis
ExamSlide 29:三種 missingness 機制:
| 機制 | 定義 | 處理 / 後果 | 例子(補充) |
|---|---|---|---|
| MCAR Missing Completely At Random | Missingness 同任何 attributes 都無關 | 用該 attribute 本身嘅值填補(例如 mean);分析整體 may be unbiased | 問卷因為郵寄途中隨機遺失 |
| MAR Missing At Random | Missingness 同其他(已觀察)variables 有關 | 根據其他 values 填補;almost always produces a bias | 年輕人較少填收入欄(缺失與 age 有關) |
| MNAR Missing Not At Random | Missingness 同未觀察到嘅量度(通常係缺失值本身)有關;informative / non-ignorable | Not possible to know the situation from the data | 高收入人士故意唔填收入 |
COM6001 Week 7 用 pandas dropna() / fillna() 同 scikit-learn SimpleImputer、KNNImputer、IterativeImputer 處理 missing values——SimpleImputer(strategy="mean") 對應「fill in values based on the attribute」(MCAR);IterativeImputer / KNNImputer 用其他 columns 估計,對應「fill in values based on other values」(MAR)。
import pandas as pd
from sklearn.impute import SimpleImputer, KNNImputer
df = pd.DataFrame({"age": [25, None, 40, 35], "income": [20, 30, None, 50]})
df.dropna() # Eliminate data objects
SimpleImputer(strategy="mean").fit_transform(df) # 用 attribute 本身 mean 填
KNNImputer(n_neighbors=2).fit_transform(df) # 用其他 attributes 相似嘅 rows 估計
4.4 Duplicate Data (Slide 30)
- Data set 可能有完全重複或幾乎重複嘅 objects。
- 合併來自 heterogeneous sources 嘅 data 時係主要問題,例如同一個人有多個 email addresses。
- Data cleaning:處理 duplicate data 嘅過程。
- Slide 問:幾時唔應該移除 duplicate data?——例如兩個真係唔同嘅人碰巧所有 attributes 都一樣(同名同年齡);或者 transaction data 入面同一客戶買兩次同一樣嘢,每次都係真實購買,刪咗會低估銷量。
5. Similarity & Dissimilarity (Section 2.2)
Slide 32 定義:
| Similarity measure | Dissimilarity measure | |
|---|---|---|
| 意思 | Numerical measure of how alike two data objects are | Numerical measure of how different two data objects are |
| 越相似時 | 數值越高 | 數值越低 |
| 範圍 | Often falls in [0, 1] | Minimum often 0;upper limit varies |
Proximity refers to a similarity or dissimilarity(兩者統稱)。
5.1 Simple Attributes (Slide 33)
對單一 attribute,兩個 objects 、 嘅 similarity 同 dissimilarity (教科書標準表):
| Attribute Type | Dissimilarity | Similarity |
|---|---|---|
| Nominal | if ; if | if ; if |
| Ordinal | (values 映射到整數 0 至 ) | |
| Interval or Ratio |
Slide 33 嘅表格係圖片,上表係教科書 Table 2.7 嘅標準內容;請對照原 slide 第 33 頁確認。
例:Ordinal attribute quality = {poor, fair, OK, good, wonderful} → {0,1,2,3,4},。 (3)、 (1):,。
6. Distance Measures
6.1 Euclidean Distance (Slides 34–35)
其中 係 dimensions(attributes)數目,、 係 objects 、 嘅第 個 attributes。Standardization is necessary, if scales differ.
如果 、:Euclidean distance ,身高差異完全被 income 淹沒。所以 scales 唔同時要先 standardize(z-score)或 min-max normalize。Chapter 4A KNN 同 Chapter 5 K-means 都會再強調呢點。
6.2 Minkowski Distance (Slides 36–38)
Minkowski Distance 係 Euclidean Distance 嘅推廣 (generalization):
係參數。Slide 37 例子:
| r | 名稱 | 計法 |
|---|---|---|
| City block / Manhattan / taxicab / L1 norm | 。Binary vectors 嘅常見例子係 Hamming distance:兩個 binary vectors 唔同嘅 bits 數目。 | |
| Euclidean distance (L2 norm) | ||
| "Supremum" ( norm, norm) | :任何 component 之間嘅最大差 |
注意:唔好將 同 混淆——所有呢啲 distances 都適用於任何 dimensions 數目 。
6.3 Worked example:四點 distance matrices
Slide 35 同 38 用四點例子展示 distance matrix(圖片未能擷取)。以下用 4 點自行計算:、、、。
例如 :差 = (2, −2)。;;。
:差 = (5, −1)。;;。
| L1 | p1 | p2 | p3 | p4 |
|---|---|---|---|---|
| p1 | 0 | 4 | 4 | 6 |
| p2 | 4 | 0 | 2 | 4 |
| p3 | 4 | 2 | 0 | 2 |
| p4 | 6 | 4 | 2 | 0 |
| L2 | p1 | p2 | p3 | p4 |
|---|---|---|---|---|
| p1 | 0 | 2.828 | 3.162 | 5.099 |
| p2 | 2.828 | 0 | 1.414 | 3.162 |
| p3 | 3.162 | 1.414 | 0 | 2 |
| p4 | 5.099 | 3.162 | 2 | 0 |
| L∞ | p1 | p2 | p3 | p4 |
|---|---|---|---|---|
| p1 | 0 | 2 | 3 | 5 |
| p2 | 2 | 0 | 1 | 3 |
| p3 | 3 | 1 | 0 | 2 |
| p4 | 5 | 3 | 2 | 0 |
對同一對點,永遠有 。 好似喺曼哈頓街道「行格仔」; 係「直線飛過去」; 只睇「差得最多嗰個維度」(好似國際象棋嘅國王行步數)。
import numpy as np
from scipy.spatial.distance import cdist
P = np.array([[0, 2], [2, 0], [3, 1], [5, 1]])
print(cdist(P, P, "cityblock")) # L1
print(cdist(P, P, "euclidean")) # L2
print(cdist(P, P, "chebyshev")) # L∞ (supremum)
print(cdist(P, P, "minkowski", p=3))
6.4 Mahalanobis Distance (Slides 39–40)
其中 係 data 嘅 covariance matrix(有啲版本會再開平方根)。佢考慮咗 attributes 之間嘅 correlation 同各自嘅 variance:沿住 data 分佈「長軸」方向嘅差距會被打折,沿「短軸」方向嘅差距會被放大。
Slide 39 例子:圖中兩個紅點,Euclidean distance 係 14.7,但 Mahalanobis distance 只係 6——因為兩點雖然直線距離遠,但係沿住 data 嘅主要分佈方向排列,以 data 嘅分佈嚟講其實「唔算遠」。Slide 40 例子:、。
Slide 39 嘅公式同散點圖、slide 40 嘅 covariance matrix 同點 A、B、C 坐標均為圖片,擷取不到;上面公式係教科書標準形式,請對照原 slide 第 39–40 頁確認具體數字。
如果 係 identity matrix(attributes 互不相關且 variance = 1),Mahalanobis distance 就退化成(平方)Euclidean distance。COM6005 嘅 z-score 就係一維版本嘅「以 standard deviation 為單位量距離」。
6.5 Common Properties of a Distance (Slide 41)
Exam設 為兩點之間嘅 distance:
- Positive definiteness: for all ,而且 only if 。
- Symmetry:。
- Triangle Inequality:。
滿足以上三條嘅 distance 叫做 metric。
驗證 triangle inequality(用上面 L2 表): ✓。
6.6 Common Properties of a Similarity (Slide 42)
- (或 maximum similarity)only if 。呢條唔一定成立,例如 cosine: 同 唔相等,但 。
- Symmetry: for all 。
7. Similarity Between Binary Vectors: SMC vs Jaccard
Slide 43:當 objects 、 只有 binary attributes,先數四個 quantities:
- : 係 0、 係 1 嘅 attributes 數目
- : 係 1、 係 0
- : 係 0、 係 0
- : 係 1、 係 1
x = 1 0 0 0 0 0 0 0 0 0
y = 0 0 0 0 0 0 1 0 0 1
(位置 7、10),(位置 1),,。
0.7
0
想像 、 係兩個客戶喺超市 10,000 件貨品嘅購買紀錄(1 = 買過)。兩人各自只買咗幾件,冇一件相同;用 SMC 計會得到接近 1(因為絕大部分係「兩個都冇買」嘅 00 match),但呢啲 00 其實冇意義。Jaccard 忽略 ,只睇「至少一方有」嘅 attributes,所以適合 asymmetric binary attributes(1 比 0 重要,例如 transaction / document data)。SMC 適合 symmetric binary(例如 gender 編碼成 0/1,兩個值同等重要)。
再練習:、 → ;;。
8. Cosine Similarity
Slide 45:如果 、 係兩個 document vectors:
係 inner product(dot product), 係 vector 嘅長度 。
d1 = 3 2 0 5 0 0 0 2 0 0
d2 = 1 0 0 0 0 0 0 1 0 2
Cosine 只睇兩個 vectors 嘅夾角(方向),唔理長度。一篇文章同佢自己 copy 兩次(所有字數 ×2)嘅 cosine = 1。所以文件長短唔同都可以公平比較主題相似度;同 Jaccard 一樣,0-0 matches 唔影響結果(0 × 0 = 0 唔加入 dot product)。對非負 vectors,cosine 喺 [0, 1]。
import numpy as np
d1 = np.array([3,2,0,5,0,0,0,2,0,0]); d2 = np.array([1,0,0,0,0,0,0,1,0,2])
print(d1 @ d2 / (np.linalg.norm(d1) * np.linalg.norm(d2))) # 0.3150
9. Information-based Measures: Entropy & Mutual Information
9.1 Information and Probability (Slide 46)
- Information 同一件事(event)嘅可能結果有關:傳送訊息、擲硬幣、量度一個 data。
- 越確定嘅結果,包含越少 information,反之亦然。例如一個兩面都係 head 嘅硬幣,擲出 head 冇提供任何 information。
- 量化嚟講:結果嘅 probability 越細,提供嘅 information 越多。
- Entropy 係最常用嘅量度。
9.2 Entropy (Slides 47–50)
對一個有 個可能結果 、概率 嘅 variable :
ExamEntropy 介乎 0 同 ,單位係 bits:即平均需要幾多 bits 去表示 嘅一個 observation。所有結果機會均等時 entropy 最大();只有一個結果必然發生時 entropy = 0。(約定 )
Coin 例子 (slide 48):head 概率 ,tail 概率 :
- Fair coin : bit
- 或 :
- Slide 問:fair four-sided die 嘅 entropy?答:4 個結果各 1/4, bits(= ,最大值)。
Sample data 版本 (slide 50):有 個 observations,第 類有 個:
Continuous data 計算較難。
| Hair Color | Count | p | |
|---|---|---|---|
| Black | 75 | 0.75 | 0.3113 |
| Brown | 15 | 0.15 | 0.4105 |
| Blond | 5 | 0.05 | 0.2161 |
| Red | 0 | 0.00 | 0 |
| Other | 5 | 0.05 | 0.2161 |
| Total | 100 | 1.0 | 1.1540 |
Maximum entropy = 。計法示範:Black 。
計數機技巧:。
9.3 Mutual Information (Slides 51–55)
Mutual Information = 一個 variable 提供關於另一個 variable 嘅 information:
係 joint entropy, 係 第 個值同 第 個值同時出現嘅概率。Discrete variables 好易計。Discrete variables 嘅 maximum 。
:Undergrad 45 (0.5184)、Grad 55 (0.4744) → 0.9928
:A 35 (0.5301)、B 50 (0.5000)、C 15 (0.4105) → 1.4406
| Status | Grade | Count | p | |
|---|---|---|---|---|
| Undergrad | A | 5 | 0.05 | 0.2161 |
| Undergrad | B | 30 | 0.30 | 0.5211 |
| Undergrad | C | 10 | 0.10 | 0.3322 |
| Grad | A | 30 | 0.30 | 0.5211 |
| Grad | B | 20 | 0.20 | 0.4644 |
| Grad | C | 5 | 0.05 | 0.2161 |
| 2.2710 | ||||
:有少少關係(Grad 學生拎 A 嘅比例較高)。
Slide 53(完全依賴):Undergrad 50 / Grad 50;Grade A 50 / B 50;joint:Undergrad-A 50、Grad-B 50、其餘 0。、、 → 。知道 status 就完全知道 grade。(此時 ,亦等於 maximum 。)
Slide 54(獨立):四個組合各 25 → → 。兩者完全冇關係。
| Value of | What it Means |
|---|---|
| and are independent. No relationship. | |
| and are dependent. The larger the value, the stronger the relationship. | |
| Knowing allows you to completely determine . | |
| Knowing allows you to completely determine . | |
| The shared information is limited by the variable with the least information. |
Entropy 會喺 Chapter 4A Decision Tree 再出現:用 entropy 量度 node impurity,而 Information Gain = 分割前 entropy − 分割後加權 entropy,本質上就係 class label 同 split attribute 之間嘅 mutual information。COM6005 嘅 Chi-square test of independence 同 都係測試「兩個 categorical variables 是否獨立」。
9.4 Maximal Information Coefficient (MIC) (Slide 56)
出自 Reshef et al. (2011, Science),將 mutual information 應用於兩個 continuous variables:
- 考慮將 variables 分成 discrete categories 嘅所有可能 binnings,限制 (、 係 X、Y 嘅 bins 數, 係樣本數)。
- 計每個 binning 嘅 mutual information。
- 用 normalize(令結果喺 0 至 1)。
- 取最高值。
10. Combining Similarities (Slides 57–58)
當 attributes 類型各異但需要一個整體 similarity:
- 對第 個 attribute 計一個喺 [0, 1] 嘅 similarity 。
- 定義 indicator : 如果第 個 attribute 係 asymmetric attribute 而兩個 objects 都係 0,或者其中一個 object 喺該 attribute 有 missing value;否則 。
- 計算:
Using Weights (slide 58):可能唔想所有 attributes 一視同仁,用 non-negative weights :
亦可定義 weighted distance:。
Slide 57 嘅最終公式同 slide 58 嘅 weighted distance 公式係圖片;上面係教科書標準形式(slide 58 嘅 weighted similarity 公式有文字擷取,與上式一致)。
,。Rating 係 ordinal {low, medium, high}→{0,1,2};Income 範圍 20K–100K;HasCar 係 asymmetric binary。
- Gender(nominal):唔同 → ,
- Rating(ordinal): → ,
- Income(ratio): → ,
- HasCar(asymmetric,兩個都 0)→ (唔計)
0.4167。
11. Data Preprocessing (Section 2.3)
Slide 60 列出六種 preprocessing:Aggregation、Sampling、Dimensionality Reduction、Feature subset selection、Discretization and Binarization、Attribute Transformation。
COM6001 Weeks 5–7 用 pandas 做嘅 groupby().agg()(Aggregation)、sample()(Sampling)、pd.cut / pd.qcut(Discretization)、pd.get_dummies(Binarization)、StandardScaler(Normalization),全部對應本 section。
11.1 Aggregation (Slides 61–63)
Combining two or more attributes (or objects) into a single attribute (or object). 目的:
- Data reduction:減少 attributes 或 objects 數目(例:PCA、Factor Analysis)。
- Change of scale:cities 合併成 regions / states / countries;days 合併成 weeks / months / years(例:moving average、kernel smoothing)。
- More "stable" data:aggregated data tends to have less variability。
Australia 降雨例子(1982–1993,3,030 個 0.5° × 0.5° grid cells):比較「average monthly precipitation 嘅 standard deviation」同「average yearly precipitation 嘅 standard deviation」嘅 histograms → 年平均嘅 variability 比月平均細(單位:cm)。
Slide 63 嘅兩個 histograms 係圖片,請對照原 slide 第 63 頁。
import pandas as pd
# 每日數據 aggregate 成每月 → 變化較細、較穩定
monthly = df.groupby(df["date"].dt.to_period("M"))["rain"].mean()
11.2 Sampling (Slides 64–67)
Sampling 係 data reduction 嘅主要技術,用於初步探索同最終分析。
- Statisticians sample:因為取得全部 data 太貴或太耗時。
- Data Mining sample:因為處理全部 data 太貴或太耗時。
"Using a sample will work almost as well as using the entire data set, if the sample is representative."
A sample is representative if it has approximately the same properties (of interest) as the original set of data.
Sample Size (slide 66):圖示 8000、2000、500 點——sample 太細會失去 data 嘅結構(例如 clusters 變得唔清楚)。
Types of Sampling (slide 67):
| 類型 | 說明 |
|---|---|
| Simple Random Sampling | 每個 item 被揀中嘅概率相等。 |
| — Sampling without replacement | 每揀中一個就從 population 移除(唔會重複)。 |
| — Sampling with replacement | 揀中後唔移除,同一個 object 可以被揀多過一次。 |
| Stratified sampling | 將 data 分成幾個 partitions(strata),再喺每個 partition 抽 random samples。適合有細小但重要嘅 group(例如 rare class)。 |
df.sample(n=500, replace=False, random_state=0) # without replacement
df.sample(n=500, replace=True, random_state=0) # with replacement
df.groupby("cls", group_keys=False).apply(lambda g: g.sample(frac=0.1)) # stratified
11.3 Curse of Dimensionality (Slide 68)
ExamWhen dimensionality increases, data becomes increasingly sparse in the space that it occupies. Clustering 同 outlier detection 依賴嘅 density 同 distance 定義變得冇咁有意義。
Slide 實驗:隨機產生 500 點,計任何兩點之間 max distance 同 min distance 嘅差(相對差)。隨住維度上升,呢個相對差趨向 0 → 「最近」同「最遠」嘅點距離差唔多,nearest neighbor 失去意義。
Slide 68 嘅曲線圖(log 相對距離差 vs 維度)係圖片,請對照原 slide 第 68 頁。
喺 1 維 放 10 點已經幾密;2 維 要 100 點先有同樣密度;10 維要 點!維度一高,所有點都「孤零零」,距離都差唔多遠。
11.4 Dimensionality Reduction (Slides 69–70)
Purpose:避免 curse of dimensionality;減少演算法所需時間同 memory;令 data 更易 visualize;可能幫助消除 irrelevant features 或減少 noise。
Techniques:Principal Components Analysis (PCA)、Singular Value Decomposition (SVD)、Factor Analysis、其他(supervised 同 non-linear techniques)。
PCA:Goal is to find a projection that captures the largest amount of variation in data。Slide 70 圖示 、 平面上一條方向 (data 分佈最闊嘅方向),將點投影落 上就由 2 維變 1 維而保留最多 variance。詳細內容會喺最後一章講。
11.5 Feature Subset Selection (Slide 71)
另一種減少 dimensionality 嘅方法(揀 subset,而唔係創造新 features):
- Redundant features:重複其他 attributes 嘅大部分或全部資訊。例:產品 purchase price 同已付 sales tax(highly correlated)。
- Irrelevant features:對當前 data mining task 冇用嘅資訊。例:student ID 對預測 GPA 通常無關。
- 有好多技術,特別係 classification 同 regression 嘅 variable selection。
Dimensionality reduction (PCA) 係將舊 attributes 組合成新 attributes(principal components 係原 features 嘅 linear combinations);Feature subset selection 係保留原有 attributes 嘅一部分,冇創造新 attribute,所以更易解釋。
11.6 Discretization (Slides 72–79)
ExamDiscretization is the process of converting a continuous attribute into an ordinal attribute:潛在無限多個值被 map 去少數 categories。常用於 classification,因為好多 classification algorithms 喺 independent 同 dependent variables 都只有少數值時表現最好。
Iris 例子(slides 73–75):Iris data set(Douglas Fisher;R: iris)有 3 個 classes(Setosa、Versicolour、Virginica)同 4 個 attributes(sepal width / length、petal width / length)。將 petal width / length discretize 成 low / medium / high 後:
- Petal width low 或 petal length low → Setosa
- Petal width medium 或 petal length medium → Versicolour
- Petal width high 或 petal length high → Virginica
點樣知道最好嘅 discretization?
- Unsupervised discretization:只喺 data values 搵 breaks(例:petal length)。
- Supervised discretization:用 class labels 去搵 breaks(例如揀令每個 bin 入面 class 最純、entropy 最低嘅切點)。
Discretization Without Using Class Labels(slides 76–79):data 有四組點同兩個 outliers(一維,加咗 random y 減少重疊):
| 方法 | 做法 | 優 / 缺點 |
|---|---|---|
| Equal interval width | 將 range 平均分成 段(每段寬度相同) | 簡單;但受 outliers 影響大,可能有 bins 幾乎冇點 |
| Equal frequency | 每個 bin 有大約相同數目嘅點(用 percentiles) | 唔怕 outliers;但可能將一個自然群組切開 |
| K-means | 用 clustering 搵自然分組 | 通常最貼近 data 嘅自然結構 |
Slides 74–79 嘅 Iris 散點圖同三種 discretization 結果圖係圖片;請對照原 slide 睇切點位置。
Values:1, 2, 3, 4, 5, 10, 11, 12, 40, 50,分 3 bins。
Equal width:,寬度 → [1, 17.33)、[17.33, 33.67)、[33.67, 50] → 各 bin 數目 8、0、2(中間 bin 空咗,outliers 拉闊咗 range)。
Equal frequency(每 bin 約 10/3 點;切點 = 33.3% 同 66.7% percentiles = 4 同 11,即 pd.qcut 結果):{1, 2, 3, 4}、{5, 10, 11}、{12, 40, 50} → 將 {10, 11, 12} 呢個自然組切開咗,12 仲同 outliers 40、50 擺埋一齊。
K-means ():大概得到 {1–5}、{10–12}、{40, 50} → 最符合自然結構。
import pandas as pd
x = pd.Series([1, 2, 3, 4, 5, 10, 11, 12, 40, 50])
pd.cut(x, bins=3) # equal interval width
pd.qcut(x, q=3) # equal frequency
11.7 Binarization (Slide 80)
- 將 continuous 或 categorical attribute map 成一個或多個 binary variables。
- 通常用於 association analysis(需要 asymmetric binary attributes)。
- 常見做法:先將 continuous attribute 轉成 categorical,再將 categorical 轉成一組 binary attributes。
- 例子:eye color;height measured as {low, medium, high} → 三個 binary 欄 height_low、height_medium、height_high。
pd.get_dummies(pd.Series(["low", "high", "medium", "low"]), prefix="height")
11.8 Attribute Transformation (Slide 81)
An attribute transform is a function that maps the entire set of values of a given attribute to a new set of replacement values such that each old value can be identified with one of the new values.
- Simple functions:、、、(slide 上符號係圖片,此為教科書標準例子)。例如 income 好 right-skewed,用 可以壓縮大數。
- Normalization:調整 attributes 之間喺 frequency of occurrence、mean、variance、range 上嘅差異;亦可移除 unwanted common signal(例如 seasonality)。
- 喺 statistics,standardization 指減 mean 再除以 standard deviation。
。Min-max → 0, 0.125, 0.375, 1。
;sample → 。
from sklearn.preprocessing import StandardScaler, MinMaxScaler
StandardScaler().fit_transform(df[["height", "income"]]) # z-score(注意 sklearn 用 population sd, ddof=0)
MinMaxScaler().fit_transform(df[["height", "income"]])
自我測驗 Self-test
Q1. 將以下 attributes 分類為 Nominal / Ordinal / Interval / Ratio,並講 discrete 定 continuous:(a) 顧客滿意度 1–5 星 (b) 身份證號碼 (c) 體重 (kg) (d) 出生年份 (e) °F 溫度 (f) 網站點擊次數
(a) Ordinal, discrete (b) Nominal, discrete (c) Ratio, continuous (d) Interval, discrete(年份 0 唔代表冇時間) (e) Interval, continuous (f) Ratio, discrete(counts)。
Q2. 點解唔可以話 20°C 係 10°C 嘅兩倍熱?Kelvin 呢?
Celsius 嘅 0 點係人為設定(水嘅冰點),唔代表冇熱量,所以只係 interval:ratio 冇意義。換做 Kelvin:293.15 / 283.15 ≈ 1.035。Kelvin 有真正零點(絕對零度),所以係 ratio,比例有意義。
Q3. x = 0 1 1 0 0 1 0 0 0 1,y = 0 1 0 0 0 1 0 1 0 1。計 SMC 同 Jaccard。
逐位:pos2 11、pos3 10、pos6 11、pos8 01、pos10 11,其餘 00。、、、。 0.8; 0.6。
Q4. ,。計 cosine similarity、Euclidean、Manhattan 同 supremum distance。
;;; 0.546。差 = (−1, −1, 2, 2): 6; 3.162; 2。
Q5. 一個 class 有 3 類,數目 8、4、4(共 16)。計 entropy 同 maximum entropy。
。 1.5 bits。 1.585。
Q6. 若 、、,計 並解讀。如果 代表咩?
0.4 > 0,、 有依賴關係。 代表知道 就可以完全決定 。 最多係 。
Q7. 一個調查入面,抑鬱程度較嚴重嘅人較少填「抑鬱分數」嗰欄。呢個係 MCAR、MAR 定 MNAR?點解?
MNAR:missingness 同缺失值本身(未觀察嘅抑鬱分數)有關,屬 informative / non-ignorable missingness,單靠 data 無法知道情況。如果缺失只同已觀察嘅 age 有關就係 MAR;完全隨機就係 MCAR。
Q8. 用 KNN 之前,attributes 分別係 height (1.5–1.8 m) 同 income ($10K–$1M),應該做咩?點解?
要做 normalization / standardization(z-score 或 min-max)。否則 Euclidean distance 幾乎完全由 income 決定(slide 34:Standardization is necessary, if scales differ)。
Q9. 比較 Equal width 同 Equal frequency discretization,各講一個缺點。
Equal width:range 被 outliers 拉闊,可能出現空 bin 或大部分點擠喺一個 bin。Equal frequency:可能將自然群組切開(相近嘅值被分去唔同 bins)。兩者都係 unsupervised(唔用 class labels)。
Q10. Curse of dimensionality 係咩?列出兩種應對方法。
維度上升時 data 喺空間變得越嚟越 sparse,density 同 distance 嘅定義失去意義(最近同最遠點距離差唔多)。應對:Dimensionality reduction(PCA、SVD、Factor Analysis)或 Feature subset selection(去除 redundant / irrelevant features)。
一頁總結 Cheat sheet
- Object = record / point / instance;Attribute = variable / field / feature / dimension。
- NOIR:Nominal()→ Ordinal(+ order)→ Interval(+ differences)→ Ratio(+ ratios,有真零點)。°C/°F、dates = interval;Kelvin、length、counts、elapsed time = ratio。
- Discrete(finite / countably infinite;binary 係特例)vs Continuous(real numbers)。
- Data sets:Record(Data Matrix、Document、Transaction)、Graph(WWW、molecules)、Ordered(sequences、genomic、spatio-temporal)。Characteristics:dimensionality、sparsity、resolution、size。
- Data quality:noise(隨機扭曲)、outliers(可以係 noise 或目標)、missing(eliminate / estimate / ignore;MCAR 無偏、MAR 依其他變數有偏、MNAR 依未觀察值無法得知)、duplicates(合併來源時常見)。
- Minkowski : Manhattan(binary 時 = Hamming)、 Euclidean、 supremum = max 差。Scales 唔同要 standardize。
- Mahalanobis :考慮 correlation(slide:Euclid 14.7 vs Mahal 6)。
- Metric:positive definiteness、symmetry、triangle inequality。Similarity: only if (cosine 唔滿足)、symmetry。
- /全部;(asymmetric binary 用 JC)。Slide 例:0.7 vs 0。
- Cosine = ;slide 例 = 。
- Entropy , bits;fair coin 1、fair 4-sided die 2;hair color 例 1.1540。
- MI ;0 = 獨立;;max = 。Slide 例:0.1624、1、0。MIC:binning()+ normalize + 取 max。
- Combined similarity = (:asymmetric 而 both 0,或 missing);可加 weights 。
- Preprocessing:Aggregation(data reduction、change of scale、less variability)、Sampling(representative!SRS with/without replacement、stratified)、Curse of dimensionality、Dim. reduction(PCA = max variance projection、SVD、FA)、Feature subset selection(redundant / irrelevant)、Discretization(continuous → ordinal;equal width / equal frequency / K-means;unsupervised vs supervised)、Binarization(association analysis,asymmetric binary)、Attribute transformation(log、;normalization;standardization = )。