File size: 11,747 Bytes
a993a7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# Chương 4: Tiền xử lý Dữ liệu
## Data Preprocessing for Knowledge Discovery

---

## 📚 Mục tiêu học tập (CLO1, CLO2, CLO3, CLO4)

Sau khi hoàn thành chương này, sinh viên có thể:
- Đánh giá chất lượng dữ liệu đa chiều (accuracy, completeness, consistency, timeliness)
- Thực hiện làm sạch dữ liệu: xử lý nhiễu, outliers, missing values
- Áp dụng các kỹ thuật biến đổi: smoothing, normalization, discretization
- Giảm số chiều dữ liệu bằng PCA, feature selection
- Feature engineering cho mô hình ML

---

## 4.1. Đa chiều Chất lượng Dữ liệu

```
    ┌──────────────────────────────────────────────────────┐
    │              DATA QUALITY DIMENSIONS                  │
    │                                                      │
    │  ┌────────────┐  ┌─────────────┐  ┌──────────────┐ │
    │  │ ACCURACY   │  │COMPLETENESS │  │ CONSISTENCY  │ │
    │  │            │  │             │  │              │ │
    │  │ Du lieu co │  │ Bao nhieu   │  │ Du lieu co   │ │
    │  │ dung khong?│  │ % bi thieu? │  │ mau thuan?   │ │
    │  │            │  │             │  │              │ │
    │  │ VD: Gia    │  │ VD: 15%     │  │ VD: Age=5    │ │
    │  │ am (-$50)  │  │ thieu email │  │ nhung Married│ │
    │  └────────────┘  └─────────────┘  └──────────────┘ │
    │                                                      │
    │  ┌────────────┐  ┌─────────────┐  ┌──────────────┐ │
    │  │ TIMELINESS │  │  VALIDITY   │  │  UNIQUENESS  │ │
    │  │            │  │             │  │              │ │
    │  │ Du lieu co │  │ Dung format │  │ Co bi trung  │ │
    │  │ cap nhat?  │  │ va range?   │  │ lap khong?   │ │
    │  │            │  │             │  │              │ │
    │  │ VD: Data   │  │ VD: Email   │  │ VD: 2 rows   │ │
    │  │ tu 2019    │  │ khong co @  │  │ cung 1 order │ │
    │  └────────────┘  └─────────────┘  └──────────────┘ │
    └──────────────────────────────────────────────────────┘
```

---

## 4.2. Kỹ thuật Làm sạch Dữ liệu

### Xử lý Missing Values

| Phương pháp | Mô tả | Khi nào dùng |
|-------------|--------|-------------|
| **Loại bỏ** | Xóa row/column có missing | Missing random, tỷ lệ thấp (<5%) |
| **Mean/Median** | Thay bằng giá trị trung bình/trung vị | Numerical, phân phối chuẩn/lệch |
| **Mode** | Thay bằng giá trị phổ biến nhất | Categorical variables |
| **Forward/Backward Fill** | Dùng giá trị trước/sau | Time series data |
| **KNN Imputation** | Dùng K neighbors gần nhất | Dữ liệu có correlation |
| **Regression** | Predict missing từ các biến khác | Strong linear relationships |
| **MICE** | Multiple Imputation by Chained Equations | Complex missing patterns |

### Xử lý Outliers

```
    Phương pháp phát hiện Outlier:
    
    1. IQR Method:
       Q1 = 25th percentile
       Q3 = 75th percentile
       IQR = Q3 - Q1
       Outlier nếu: x < Q1 - 1.5*IQR hoặc x > Q3 + 1.5*IQR
    
    2. Z-Score Method:
       z = (x - mean) / std
       Outlier nếu: |z| > 3
    
    3. Modified Z-Score (robust):
       MAD = median(|xi - median(x)|)
       Modified_Z = 0.6745 * (xi - median(x)) / MAD
       Outlier nếu: |Modified_Z| > 3.5
    
    Xử lý:
    - Capping/Winsorizing: Thay outlier bằng percentile 1%/99%
    - Log transform: Giảm skewness
    - Loại bỏ: Nếu chắc chắn là lỗi dữ liệu
    - Giữ nguyên: Nếu outlier có ý nghĩa business (VD: đơn hàng lớn)
```

---

## 4.3. Data Integration & Deduplication

### Entity Resolution

```
    Record A: "Sao Paulo", "SP", "sao_paulo@email.com"
    Record B: "São Paulo", "SP", "saopaulo@email.com"  
    Record C: "S. Paulo",  "SP", "sao_paulo@email.com"
    
    → Tất cả là cùng 1 entity!
    
    Kỹ thuật:
    1. Exact matching (= )
    2. Fuzzy matching (Levenshtein distance, Jaro-Winkler)
    3. Phonetic matching (Soundex, Metaphone)
    4. ML-based matching (trained classifier)
```

---

## 4.4. Biến đổi Dữ liệu (Transformation)

### Smoothing Methods

| Method | Công thức | Use case |
|--------|-----------|----------|
| **Moving Average** | MA(k) = (1/k) * Σ x_i | Time series noise reduction |
| **Weighted MA** | WMA = Σ w_i * x_i / Σ w_i | Recent data more important |
| **Exponential Smoothing** | S_t = α*x_t + (1-α)*S_{t-1} | Adaptive smoothing |
| **Binning** | Group into bins, replace with bin mean/median | Discretization |

---

## 4.5. Data Reduction: Giảm số chiều

### PCA (Principal Component Analysis)

```
    Original: 10 features          PCA: 3 components (95% variance)
    ┌──────────────────┐          ┌──────────────────┐
    │ x1 x2 x3 ... x10│    →     │ PC1  PC2  PC3    │
    │                  │  PCA     │                  │
    │ 1000 x 10        │          │ 1000 x 3         │
    └──────────────────┘          └──────────────────┘
    
    Bước thực hiện:
    1. Standardize dữ liệu (mean=0, std=1)
    2. Tính Covariance Matrix
    3. Tính Eigenvalues & Eigenvectors
    4. Chọn top-k components (giải thích 95%+ variance)
    5. Transform dữ liệu sang không gian mới
```

### Feature Selection Methods

| Method | Type | Mô tả |
|--------|------|-------|
| **Variance Threshold** | Filter | Loại features có variance thấp |
| **Correlation** | Filter | Loại features có correlation cao với nhau |
| **Chi-squared** | Filter | Đánh giá independence giữa feature và target |
| **Mutual Information** | Filter | Đo lượng thông tin chung |
| **Forward Selection** | Wrapper | Thêm feature từng cái, chọn cái tốt nhất |
| **Backward Elimination** | Wrapper | Bỏ feature từng cái, bỏ cái kém nhất |
| **L1 Regularization** | Embedded | Lasso tự động zero-out features |
| **Tree Importance** | Embedded | Feature importance từ Random Forest |

---

## 4.6. Discretization

### Chuyển continuous → categorical

```
    Binning Methods:
    
    1. Equal-width (equal interval):
       price: [0-100], [100-200], [200-300], [300-400], [400-500]
       → Đơn giản nhưng sensitive với outliers
    
    2. Equal-frequency (equal depth):
       price: Mỗi bin có 20% dữ liệu
       → Cân bằng hơn, nhưng mất ý nghĩa range
    
    3. Entropy-based (supervised):
       Chọn split points tối ưu cho classification target
       → Tốt nhất cho ML, nhưng cần label
    
    4. Clustering-based:
       Dùng K-Means để tìm natural groups
       → Data-driven, phù hợp cho khám phá
```

---

## 4.7. Chuẩn hóa Dữ liệu (Normalization)

```
    1. Min-Max Normalization:
       x' = (x - min) / (max - min)
       Range: [0, 1]
       Ưu: Giữ nguyên distribution shape
       Nhược: Sensitive với outliers
    
    2. Z-Score Standardization:
       x' = (x - μ) / σ
       Range: unbounded (typically -3 to +3)
       Ưu: Robust hơn với outliers
       Nhược: Không bounded
    
    3. Decimal Scaling:
       x' = x / 10^j (j = smallest int so that max(|x'|) < 1)
       VD: 345 → 0.345 (j=3)
    
    4. Robust Scaling:
       x' = (x - median) / IQR
       Ưu: Rất robust với outliers
       Nhược: Ít phổ biến
```

---

## 4.8. Feature Engineering

### Tạo features mới từ dữ liệu Olist

```
    Raw Data                         Engineered Features
    ┌──────────────────────┐        ┌──────────────────────────────┐
    │ order_purchase_ts    │   →    │ hour_of_day                  │
    │                      │        │ day_of_week                  │
    │                      │        │ is_weekend                   │
    │                      │        │ month                        │
    │                      │        │ days_since_first_order       │
    ├──────────────────────┤        ├──────────────────────────────┤
    │ price, freight       │   →    │ freight_ratio (freight/price)│
    │                      │        │ price_category (binned)      │
    │                      │        │ is_free_shipping             │
    ├──────────────────────┤        ├──────────────────────────────┤
    │ review_comment       │   →    │ comment_length               │
    │                      │        │ has_comment (bool)           │
    │                      │        │ sentiment_score              │
    ├──────────────────────┤        ├──────────────────────────────┤
    │ customer_city,       │   →    │ distance_to_seller           │
    │ seller_city          │        │ same_state (bool)            │
    │                      │        │ region_pair                  │
    ├──────────────────────┤        ├──────────────────────────────┤
    │ product dimensions   │   →    │ volume                       │
    │ (l, w, h, weight)   │        │ density (weight/volume)      │
    │                      │        │ is_heavy (>5kg)              │
    └──────────────────────┘        └──────────────────────────────┘
```

---

## 🔬 Labs

- [`lab-04-data-cleaning.py`](lab-04-data-cleaning.py) — Làm sạch dữ liệu Olist
- [`lab-04-normalization.py`](lab-04-normalization.py) — Chuẩn hóa dữ liệu
- [`lab-04-dimensionality.py`](lab-04-dimensionality.py) — PCA & Feature Selection
- [`lab-04-feature-engineering.py`](lab-04-feature-engineering.py) — Feature Engineering

---

## 📝 Câu hỏi ôn tập

1. Liệt kê 6 chiều chất lượng dữ liệu. Cho ví dụ vi phạm với dataset Olist.
2. So sánh 5 phương pháp xử lý Missing Values. Khi nào dùng phương pháp nào?
3. IQR method phát hiện outlier như thế nào? Tính toán cho cột `price` có Q1=50, Q3=200.
4. PCA giảm chiều như thế nào? Giải thích "explained variance ratio".
5. Cho 3 ví dụ Feature Engineering cho dataset Olist mà có ý nghĩa business.