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
- Mean 對 outliers 敏感 → 用 median 或 trimmed mean;variance / sd 亦對 outliers 敏感 → 用 IQR、AAD、MAD 等。
- Percentile 定義:-th percentile 令 嘅 observed values 細過 ;median = 50th percentile。
- Box plot 嘅組成:median、25th / 75th percentiles(box)、whiskers、outliers;用嚟比較 attributes。
- Histogram 形狀受 bins 數目影響;scatter plot array 總結多對 attributes 關係。
- 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。
COM6005 Module 1 Descriptive Statistics 同本 chapter 嘅 summary statistics 基本一樣(mean、median、variance、percentile、box plot);COM6001 pandas 嘅 df.describe()、value_counts()、df.hist()、df.boxplot() 就係實際操作。
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。
對應 Chapter 2 NOIR:Nominal attribute 只有 distinctness,所以只可以用 mode / frequency(計 mean 冇意義)。
2.2 Percentiles (Slide 8)
對 continuous data,percentile 更有用。
Given an ordinal or continuous attribute and a number between 0 and 100, the -th percentile is a value of such that of the observed values of are less than .
例如 50th percentile 係 ,令 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)
其中 係排序後第 個值。
Slide 9 嘅 mean / median 公式係圖片;上面係教科書標準公式,請對照原 slide 第 9 頁。
ExamThe mean is very sensitive to outliers. 所以亦常用 median 或 trimmed mean(先去掉頭尾各 嘅極端值再計 mean)。
Data(月薪,千元):12, 14, 15, 15, 16, 18, 20, 22, 25, 200()
- 35.7(被 200 嚴重拉高)
- Median( 偶數) 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 。
- Variance 或 standard deviation 係最常用嘅 spread 量度:
不過 variance 都對 outliers 敏感,所以常用其他量度(教科書列出):
Slide 10 嘅 variance 公式同「other measures」公式係圖片 / 嵌入物件;上面 AAD (absolute average deviation)、MAD (median absolute deviation)、IQR (interquartile range) 係教科書標準內容,請對照原 slide 第 10 頁確認 slide 實際列出邊幾個。
Data:2, 4, 4, 5, 7, 8()。。
Deviations:−3, −1, −1, 0, 2, 3 → squares 9, 1, 1, 0, 4, 9 → sum = 24。
4.8; 2.191; 6; 1.667。
如果將 8 改做 80:range 變 78,variance 大增,但 IQR 幾乎唔變 → IQR 係 robust measure。
Sample variance 分母係 (唔係 )。pandas Series.var() 預設 ddof=1(),numpy np.var() 預設 ddof=0()——兩者答案會唔同!
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 會消失)。
呢度嘅 dimensionality reduction(例如 PCA 投影到 2D)同 sampling 都係 Chapter 2 Data Preprocessing 嘅技術。
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(教科書版本),或常見軟件版本: 至 範圍內嘅最遠值 |
| 獨立點 | 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。
Data:1, 3, 4, 5, 6, 7, 8, 9, 30。;、(用 pandas 預設 linear interpolation;如用「上下半數 data 嘅 median」方法會得 3.5 / 8.5,結論一樣);。
用 規則:, → 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( 軸一個 attribute, 軸另一個)。
- 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。
Chapter 5 Cluster Validity 會再用「按 cluster labels 排序嘅 similarity matrix」去視覺檢查 clustering 好唔好(slide 74–76)——同呢度「按 class 排序嘅 matrix plot」係同一個 idea。
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 plot | Distribution 摘要(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 coordinates | High-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 較好。
19.5; 8.5; 97。100 係 outlier,mean 被大幅拉高,而 median 唔受影響,更能代表典型值(slide 9:mean is very sensitive to outliers)。
Q3. Data:4, 6, 8, 10, 12。計 sample variance 同 standard deviation。
; → 40; 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 用。
- -th percentile : 嘅值細過 ;median = 50th;。
- Mean 對 outliers 敏感 → median / trimmed mean。
- Range ;variance ,亦對 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 好重要。