All Revision Notes

COM6004 Data Mining · Chapter 3

Data Exploration & Visualization

COM6004 · Chapter 3 · Source: COM6004_Chapter_3_Data_Visualization.pptx (26 slides) · Data Exploration, Summary Statistics, Data Visualization

Contents · 10 sections

🎯 本講重點 (Learning outcomes)

  • 講出 Data Exploration 嘅定義同兩大動機。
  • 計算同解讀 Summary Statistics:frequency、mode、percentile、mean、median、trimmed mean、range、variance / standard deviation(以及 robust 替代如 IQR)。
  • 理解 visualization 嘅定義、data representation 同 attribute selection 概念。
  • 識用同解讀 Histogram、Box Plot、Scatter Plot (array)、Matrix Plot(data matrix / correlation matrix)、Parallel Coordinates Plot,並知道各自適用情況(以 Iris data set 為例)。

⭐ 考試必溫 Top-5

  1. Mean 對 outliers 敏感 → 用 median 或 trimmed mean;variance / sd 亦對 outliers 敏感 → 用 IQR、AAD、MAD 等。
  2. Percentile 定義:pp-th percentile xpx_p 令 p%p\% 嘅 observed values 細過 xpx_p;median = 50th percentile。
  3. Box plot 嘅組成:median、25th / 75th percentiles(box)、whiskers、outliers;用嚟比較 attributes。
  4. Histogram 形狀受 bins 數目影響;scatter plot array 總結多對 attributes 關係。
  5. Parallel coordinates:每個 object 係一條線;attributes 排序影響能否睇到 groupings;matrix plot 要先 standardize。

1. Data Exploration

Slide 4 定義:A preliminary exploration of the data to better understand its characteristics.

Exam主要動機 (key motivations):

  • Helping to select the right tool for preprocessing or analysis(例如見到 data 好 skewed 就考慮 log transform;見到 clusters 形狀唔係圓就唔用 K-means)。
  • Making use of humans' abilities to recognize patterns:人可以認出 data analysis tools 捕捉唔到嘅 patterns。

本 chapter 集中講兩樣:summary statistics 同 data visualization。

2. Summary Statistics

Slide 6:Summary statistics are numbers that summarize properties of the data. 總結嘅 properties 包括 frequency、location、spread。例如 location → mean;spread → standard deviation。大部分 summary statistics 可以 single pass through the data(掃一次 data)就計到。

2.1 Frequency and Mode (Slide 7)

  • 一個 attribute value 嘅 frequency = 該值喺 data set 出現嘅百分比。例:attribute 'gender',喺有代表性嘅人口中 'female' 大約出現 50%。
  • Mode = 最常出現嘅 attribute value。
  • Frequency 同 mode 通常用於 categorical data。

2.2 Percentiles (Slide 8)

對 continuous data,percentile 更有用。

⭐ 考試重點:Percentile 定義

Given an ordinal or continuous attribute xx and a number pp between 0 and 100, the pp-th percentile is a value xpx_p of xx such that p%p\% of the observed values of xx are less than xpx_p.

例如 50th percentile 係 x50%x_{50\%},令 50% 嘅值細過佢 → 即 median。25th / 75th percentiles 叫 first / third quartile (Q1 / Q3)。

注意:percentile 只需要 order,所以 ordinal attribute 都可以計(但 nominal 唔得)。

2.3 Measures of Location: Mean and Median (Slide 9)

mean(x)=xˉ=1m∑i=1mxi\text{mean}(x) = \bar{x} = \frac{1}{m}\sum_{i=1}^{m} x_i
median(x)={x(r+1)if m=2r+1 (odd)12(x(r)+x(r+1))if m=2r (even)\text{median}(x) = \begin{cases} x_{(r+1)} & \text{if } m = 2r+1 \text{ (odd)} \\ \tfrac{1}{2}\left(x_{(r)} + x_{(r+1)}\right) & \text{if } m = 2r \text{ (even)} \end{cases}

其中 x(i)x_{(i)} 係排序後第 ii 個值。

🖼️ 圖片內容

Slide 9 嘅 mean / median 公式係圖片;上面係教科書標準公式,請對照原 slide 第 9 頁。

ExamThe mean is very sensitive to outliers. 所以亦常用 median 或 trimmed mean(先去掉頭尾各 p/2 %p/2\,\% 嘅極端值再計 mean)。

💡 Worked example

Data(月薪,千元):12, 14, 15, 15, 16, 18, 20, 22, 25, 200(m=10m = 10)

  • Mean=(12+14+15+15+16+18+20+22+25+200)/10=357/10=\text{Mean} = (12+14+15+15+16+18+20+22+25+200)/10 = 357/10 = 35.7(被 200 嚴重拉高)
  • Median(mm 偶數)=(16+18)/2== (16 + 18)/2 = 17
  • 20% trimmed mean:去掉最細 10%(12)同最大 10%(200)→ (14+15+15+16+18+20+22+25)/8 = 145/8 = 18.125
  • Mode = 15

結論:有 outlier 時,median 同 trimmed mean 更能代表「典型」值。

2.4 Measures of Spread: Range and Variance (Slide 10)

  • Range =max⁡−min⁡= \max - \min。
  • Variance sx2s_x^2 或 standard deviation sxs_x 係最常用嘅 spread 量度:
variance(x)=sx2=1m−1∑i=1m(xi−xˉ)2\text{variance}(x) = s_x^2 = \frac{1}{m-1}\sum_{i=1}^{m}(x_i - \bar{x})^2

不過 variance 都對 outliers 敏感,所以常用其他量度(教科書列出):

AAD(x)=1m∑i=1m∣xi−xˉ∣,MAD(x)=median({∣x1−xˉ∣,…,∣xm−xˉ∣}),IQR(x)=x75%−x25%\text{AAD}(x) = \frac{1}{m}\sum_{i=1}^{m}|x_i-\bar{x}|, \quad \text{MAD}(x) = \text{median}\big(\{|x_1-\bar{x}|,\dots,|x_m-\bar{x}|\}\big), \quad \text{IQR}(x) = x_{75\%} - x_{25\%}
🖼️ 圖片內容

Slide 10 嘅 variance 公式同「other measures」公式係圖片 / 嵌入物件;上面 AAD (absolute average deviation)、MAD (median absolute deviation)、IQR (interquartile range) 係教科書標準內容,請對照原 slide 第 10 頁確認 slide 實際列出邊幾個。

💡 Worked example(延續)

Data:2, 4, 4, 5, 7, 8(m=6m = 6)。Mean=30/6=5\text{Mean} = 30/6 = 5。

Deviations:−3, −1, −1, 0, 2, 3 → squares 9, 1, 1, 0, 4, 9 → sum = 24。

Variance=24/(6−1)=\text{Variance} = 24/(6 - 1) = 4.8;sd=4.8=\text{sd} = \sqrt{4.8} = 2.191;Range=8−2=\text{Range} = 8 - 2 = 6;AAD=(3+1+1+0+2+3)/6=AAD = (3+1+1+0+2+3)/6 = 1.667。

如果將 8 改做 80:range 變 78,variance 大增,但 IQR 幾乎唔變 → IQR 係 robust measure。

⚠️ 常見錯誤

Sample variance 分母係 m−1m - 1(唔係 mm)。pandas Series.var() 預設 ddof=1(m−1m - 1),numpy np.var() 預設 ddof=0(mm)——兩者答案會唔同!

import pandas as pd
x = pd.Series([12, 14, 15, 15, 16, 18, 20, 22, 25, 200])
x.mean(), x.median(), x.mode()[0]
from scipy import stats
stats.trim_mean(x, 0.1)              # 每邊去 10% → 18.125
x.max() - x.min(), x.var(), x.std()  # range, variance (m-1), sd
x.quantile(0.75) - x.quantile(0.25)  # IQR
x.describe()                         # count/mean/std/min/25%/50%/75%/max

3. Data Visualization: 概念

Slide 12 定義:Visualization is the conversion of data into a visual or tabular format so that the characteristics of the data and the relationships among data items or attributes can be analyzed or reported.

Visualization 係 data exploration 最強大、最吸引嘅技術之一,因為人類有高度發展嘅能力去分析以視覺呈現嘅大量資訊:

  • Can detect general patterns and trends
  • Can detect outliers and unusual patterns

3.1 Data Representation (Slide 13)

The mapping of information to a visual format. Data objects、attributes 同 objects 之間嘅 relationships 被轉譯成 graphical elements:points、lines、shapes、colors。

  • Objects 通常表示為 points。
  • Attribute values 可以用點嘅 position 或點嘅特徵(color、size、shape)表示。
  • 如果用 position,點之間嘅關係(例如形成 groups,或者某點係 outlier)就好易察覺。

3.2 Attribute Selection (Slide 14)

The elimination or the de-emphasis of certain objects and attributes.

  • 揀 attributes 嘅 subset:常用 dimensionality reduction 將維度減到 2 或 3;或者逐對 (pairs) attributes 考慮。
  • 揀 objects 嘅 subset:螢幕一個區域只能顯示咁多點;可以 sample,但要保留 sparse 區域嘅點(否則 outliers / 細 clusters 會消失)。

3.3 Iris Sample Data Set (Slide 15)

好多 exploratory techniques 用 Iris Plant data set 示範(R: data(iris)):

  • 三個 flower types(classes):Setosa、Virginica、Versicolour
  • 四個 non-class attributes:Sepal width and length、Petal width and length

Slide 提到會用 R 將 visualization techniques 應用喺 Iris data set。以下同時提供 Python 版本方便對照。

4. Histograms

Slide 16:

  • 通常顯示單一 variable 嘅值嘅 distribution。
  • 將值分成 bins,再畫 bar plot 顯示每個 bin 嘅 objects 數目。
  • 每條 bar 嘅高度 = 該 bin 嘅 objects 數目。
  • ExamShape of histogram depends on the number of bins.
🖼️ 圖片內容

Slide 16 有兩幅 Iris petal width 嘅 histograms(例如 10 bins vs 20 bins),係圖片;請對照原 slide 第 16 頁。

💡 直覺理解

Bins 太少:所有細節被抹平(例如 Iris petal length 嘅兩個峰合成一個);bins 太多:好多鋸齒,noise 被放大。所以試幾個 bin 數再判斷 distribution 形狀。

import seaborn as sns, matplotlib.pyplot as plt
iris = sns.load_dataset("iris")
iris["petal_width"].plot.hist(bins=10); plt.show()
iris["petal_width"].plot.hist(bins=20); plt.show()   # 形狀會唔同
# R: hist(iris$Petal.Width, breaks = 10)

5. Box Plots

Slide 17:另一種顯示 data distribution 嘅方法。Box plot 嘅基本組成(教科書標準):

部分代表
Box 底線25th percentile (Q1)
Box 入面條線50th percentile (median)
Box 頂線75th percentile (Q3);box 高度 = IQR
Whiskers延伸到 10th / 90th percentile(教科書版本),或常見軟件版本:Q1−1.5⋅IQRQ_1 - 1.5 \cdot IQR 至 Q3+1.5⋅IQRQ_3 + 1.5 \cdot IQR 範圍內嘅最遠值
獨立點Outliers(whiskers 以外嘅值)
🖼️ 圖片內容

Slide 17 嘅 box plot 結構圖同 slide 18 嘅 Iris box plots 係圖片;上表係教科書標準結構,whisker 定義請以 slide 第 17 頁圖為準。

Slide 18:Box plots can be used to compare attributes——將 Iris 四個 attributes 並排畫,即刻見到邊個 attribute 範圍大、中位數高、有冇 outliers。

⭐ 考試重點:Box plot 計算題型

Data:1, 3, 4, 5, 6, 7, 8, 9, 30。Median=6\text{Median} = 6;Q1=4Q_1 = 4、Q3=8Q_3 = 8(用 pandas 預設 linear interpolation;如用「上下半數 data 嘅 median」方法會得 3.5 / 8.5,結論一樣);IQR=4IQR = 4。

用 1.5⋅IQR1.5 \cdot IQR 規則:lower fence=4−6=−2\text{lower fence} = 4 - 6 = -2,upper fence=8+6=14\text{upper fence} = 8 + 6 = 14 → 30 係 outlier,上 whisker 延伸到 9,下 whisker 到 1。

iris.boxplot(column=["sepal_length", "sepal_width", "petal_length", "petal_width"])
iris.boxplot(column="petal_length", by="species")   # 按 class 比較
# R: boxplot(iris[, 1:4])

6. Scatter Plots

Slide 19:

  • Attribute values determine the position(xx 軸一個 attribute,yy 軸另一個)。
  • 2D scatter plot 最常見,亦可以有 3D。
  • 可以用 marker 嘅 size、shape、color 顯示額外 attributes(例如用顏色代表 class)。
  • Arrays of scatter plots(scatter plot matrix)可以精簡地總結幾對 attributes 之間嘅關係。

Slide 20:Iris 嘅 scatter plot array——4 個 attributes 形成 4 × 4 格,每格係一對 attributes,以顏色分 class。從中可見 Setosa 喺 petal length / width 上同其他兩類明顯分開。

🖼️ 圖片內容

Slide 20 嘅 scatter plot array 係圖片,請對照原 slide 第 20 頁。

sns.pairplot(iris, hue="species")      # scatter plot array,顏色 = class
# R: pairs(iris[, 1:4], col = iris$Species)

7. Matrix Plots

Slide 21:

  • 將 data matrix 以圖像(每格顏色代表數值)顯示。
  • 當 objects 按 class 排序時特別有用(同 class 嘅行排埋一齊,可以見到 class 之間 attribute 值嘅分別)。
  • Exam通常會先 normalize attributes(standardize 成 mean 0、standard deviation 1),防止某個 attribute 主導個 plot。
  • Similarity 或 distance matrices 嘅 plot 亦有用,可視覺化 objects 之間嘅關係。
  • 典型例子:data matrix plots 同 correlation matrix plots。

Slide 22:Iris Data Matrix(顏色 bar 以 "standard deviation" 為單位,即 standardized 後嘅值)。Slide 23:Iris Correlation Matrix(4 × 4 attributes 之間嘅 correlation)。

🖼️ 圖片內容

Slides 22–23 嘅 matrix plots 係圖片,請對照原 slide。

from sklearn.preprocessing import StandardScaler
X = StandardScaler().fit_transform(iris.iloc[:, :4])        # 先 standardize
plt.imshow(X, aspect="auto", cmap="coolwarm"); plt.colorbar(); plt.show()   # data matrix plot
sns.heatmap(iris.iloc[:, :4].corr(), annot=True)            # correlation matrix plot

8. Parallel Coordinates Plots

Slide 24:

  • 用嚟畫 high-dimensional data 嘅 attribute values。
  • 唔用互相垂直嘅軸,而係用一組平行嘅軸 (parallel axes)。
  • 每個 object 喺每條對應軸上畫一個點,再將啲點連成一條線 → each object is represented as a line。
  • 代表同一 class 嘅線通常會聚埋一齊(至少喺某啲 attributes 上)。
  • ExamOrdering of attributes is important in seeing such groupings.

Slide 25:Iris 嘅 parallel coordinates plot——可見 Setosa 嘅線喺 petal length / width 軸上集中喺低位,同另外兩類分開。

🖼️ 圖片內容

Slide 25 有兩幅 parallel coordinates plots(可能係唔同 attribute 次序),係圖片;請對照原 slide 第 25 頁。

from pandas.plotting import parallel_coordinates
parallel_coordinates(iris, "species"); plt.show()
# R: library(MASS); parcoord(iris[, 1:4], col = as.numeric(iris$Species))
⭐ 考試重點:揀邊種圖?
圖顯示適合問題注意
Histogram單一 variable distribution「呢個 attribute 分佈係點?有冇幾個峰?」形狀受 bins 數影響
Box plotDistribution 摘要(median、quartiles、outliers)「比較幾個 attributes / classes 嘅分佈」見唔到多峰
Scatter plot (array)兩個 attributes 之間關係「兩者有冇 correlation?有冇 clusters?」可用 color / shape 加 class
Matrix plot成個 data / similarity / correlation matrix「objects 按 class 排序後有冇明顯 pattern?」先 standardize
Parallel coordinatesHigh-dimensional objects(每個一條線)「多個 attributes 一齊睇,classes 點分開?」Attributes 次序好重要

自我測驗 Self-test

Q1. Data exploration 嘅定義同兩個主要動機係咩?

定義:A preliminary exploration of the data to better understand its characteristics。動機:(1) 幫助揀適合嘅 preprocessing / analysis 工具;(2) 利用人類認 pattern 嘅能力(人可以認出 analysis tools 捕捉唔到嘅 patterns)。

Q2. Data:3, 5, 7, 8, 9, 11, 13, 100。計 mean、median、range,並講點解 median 較好。

Mean=156/8=\text{Mean} = 156/8 = 19.5;Median=(8+9)/2=\text{Median} = (8 + 9)/2 = 8.5;Range=100−3=\text{Range} = 100 - 3 = 97。100 係 outlier,mean 被大幅拉高,而 median 唔受影響,更能代表典型值(slide 9:mean is very sensitive to outliers)。

Q3. Data:4, 6, 8, 10, 12。計 sample variance 同 standard deviation。

Mean=8\text{Mean} = 8;(x−xˉ)2=16,4,0,4,16(x-\bar{x})^2 = 16, 4, 0, 4, 16 → 40;variance=40/4=\text{variance} = 40/4 = 10;sd=10=\text{sd} = \sqrt{10} = 3.162。

Q4. 解釋「the 80th percentile 係 65 分」嘅意思。對 nominal attribute 可以計 percentile 嗎?

代表 80% 嘅 observed values 細過 65 分。Nominal attribute 冇 order,所以唔可以計 percentile(只可以用 frequency / mode)。

Q5. 點解 histogram 嘅結論可能誤導?

因為 histogram 形狀取決於 bins 數目:bins 太少會抹平細節(例如雙峰變單峰),太多會出現 noise 鋸齒。應試幾種 bin 數。

Q6. 畫 data matrix plot 之前點解要 standardize?

因為 attributes 嘅 scale 唔同(例如一個 0–1、一個 0–1000),唔 standardize 嘅話顏色會被大 scale 嘅 attribute 主導,其他 attributes 嘅變化睇唔到。Standardize 成 mean 0、sd 1 後每個 attribute 公平比較。

Q7. Parallel coordinates plot 點樣表示一個 object?有咩要注意?

每個 attribute 一條平行軸,object 喺每條軸上有一點,連起嚟成一條線。同 class 嘅線傾向聚埋;attributes 嘅排列次序會影響能否睇到 groupings。

Q8. 想比較 Iris 三個 species 嘅 petal length 分佈,同時睇有冇 outliers,用咩圖最好?寫出 Python 一行。

Box plot(按 species 分組):iris.boxplot(column="petal_length", by="species")。

一頁總結 Cheat sheet

⭐ 考前速記
  • Data exploration:preliminary exploration to understand characteristics;動機:揀啱工具 + 利用人類 pattern recognition。
  • Summary statistics:frequency、location、spread;多數 single pass 計到。
  • Frequency / mode:categorical data 用。
  • pp-th percentile xpx_p:p%p\% 嘅值細過 xpx_p;median = 50th;IQR=Q3−Q1IQR = Q_3 - Q_1。
  • Mean 對 outliers 敏感 → median / trimmed mean。
  • Range =max⁡−min⁡= \max - \min;variance s2=1m−1∑(x−xˉ)2s^2 = \frac{1}{m-1}\sum(x-\bar x)^2,亦對 outliers 敏感 → AAD、MAD、IQR。
  • Visualization:轉成 visual / tabular format 以分析或報告;detect patterns、trends、outliers。
  • Representation:objects → points;attributes → position / color / size / shape。
  • Selection:減 attributes(dim. reduction 到 2–3 維或逐對)同 objects(sample 但保留 sparse 區)。
  • Iris:3 classes(Setosa、Versicolour、Virginica),4 attributes(sepal / petal × length / width)。
  • Histogram:單一 variable;shape depends on #bins。
  • Box plot:median、quartiles、whiskers、outliers;比較 attributes。
  • Scatter plot:position = attribute values;size / shape / color 加 attributes;scatter plot array 總結多對關係。
  • Matrix plot:按 class 排序有用;先 standardize(mean 0、sd 1);data matrix / correlation matrix。
  • Parallel coordinates:平行軸,每 object 一條線;同 class 線聚埋;attribute ordering 好重要。