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|
|
| 1 |
+
"""
|
| 2 |
+
Lab 4: Data Cleaning & Preprocessing
|
| 3 |
+
=====================================
|
| 4 |
+
BIM5021 - Nhà kho dữ liệu và Tích hợp
|
| 5 |
+
Chương 4: Tiền xử lý dữ liệu
|
| 6 |
+
|
| 7 |
+
Mục tiêu:
|
| 8 |
+
- Đánh giá chất lượng dữ liệu (Data Quality Assessment)
|
| 9 |
+
- Xử lý Missing Values (nhiều phương pháp)
|
| 10 |
+
- Phát hiện và xử lý Outliers (IQR, Z-score)
|
| 11 |
+
- Normalization (Min-Max, Z-Score, Robust)
|
| 12 |
+
- PCA (Principal Component Analysis)
|
| 13 |
+
- Feature Engineering cho Olist dataset
|
| 14 |
+
|
| 15 |
+
Yêu cầu: pip install pandas numpy scikit-learn matplotlib seaborn
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import pandas as pd
|
| 19 |
+
import numpy as np
|
| 20 |
+
import matplotlib
|
| 21 |
+
matplotlib.use('Agg')
|
| 22 |
+
import matplotlib.pyplot as plt
|
| 23 |
+
from sklearn.preprocessing import MinMaxScaler, StandardScaler, RobustScaler
|
| 24 |
+
from sklearn.decomposition import PCA
|
| 25 |
+
from sklearn.impute import KNNImputer
|
| 26 |
+
import warnings
|
| 27 |
+
warnings.filterwarnings('ignore')
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# ==============================================================================
|
| 31 |
+
# PHẦN 1: Tạo Sample Dataset (mô phỏng Olist)
|
| 32 |
+
# ==============================================================================
|
| 33 |
+
|
| 34 |
+
def create_sample_olist():
|
| 35 |
+
"""Tạo sample dataset mô phỏng Olist với các vấn đề data quality."""
|
| 36 |
+
np.random.seed(42)
|
| 37 |
+
n = 1000
|
| 38 |
+
|
| 39 |
+
# Tạo dữ liệu với các vấn đề data quality có chủ đích
|
| 40 |
+
df = pd.DataFrame({
|
| 41 |
+
'order_id': [f'ORD_{i:05d}' for i in range(n)],
|
| 42 |
+
'price': np.concatenate([
|
| 43 |
+
np.random.lognormal(4, 1, n-10), # Normal prices
|
| 44 |
+
np.array([-50, -10, 0, 0, 0, # Negative/zero (errors)
|
| 45 |
+
5000, 8000, 12000, 15000, 20000]) # Outliers
|
| 46 |
+
]),
|
| 47 |
+
'freight_value': np.concatenate([
|
| 48 |
+
np.random.exponential(30, n-5),
|
| 49 |
+
np.array([np.nan, np.nan, np.nan, -5, 500]) # Missing + errors
|
| 50 |
+
]),
|
| 51 |
+
'review_score': np.random.choice([1, 2, 3, 4, 5, np.nan], n,
|
| 52 |
+
p=[0.05, 0.05, 0.1, 0.3, 0.4, 0.1]),
|
| 53 |
+
'product_weight_g': np.concatenate([
|
| 54 |
+
np.random.lognormal(6, 1.2, n-3),
|
| 55 |
+
np.array([np.nan, np.nan, 0]) # Missing + zero
|
| 56 |
+
]),
|
| 57 |
+
'product_length_cm': np.random.uniform(5, 100, n),
|
| 58 |
+
'product_height_cm': np.random.uniform(2, 80, n),
|
| 59 |
+
'product_width_cm': np.random.uniform(5, 60, n),
|
| 60 |
+
'customer_state': np.random.choice(
|
| 61 |
+
['SP', 'RJ', 'MG', 'RS', 'PR', 'BA', 'SC', None],
|
| 62 |
+
n, p=[0.3, 0.15, 0.1, 0.1, 0.08, 0.07, 0.05, 0.15]
|
| 63 |
+
),
|
| 64 |
+
'delivery_days': np.concatenate([
|
| 65 |
+
np.random.exponential(10, n-5),
|
| 66 |
+
np.array([np.nan, np.nan, -2, 0, 120]) # Missing + errors + outlier
|
| 67 |
+
]),
|
| 68 |
+
'order_status': np.random.choice(
|
| 69 |
+
['delivered', 'shipped', 'canceled', 'processing', 'DELIVERED', 'Delivered'],
|
| 70 |
+
n, p=[0.6, 0.1, 0.05, 0.05, 0.1, 0.1]
|
| 71 |
+
),
|
| 72 |
+
})
|
| 73 |
+
|
| 74 |
+
# Shuffle
|
| 75 |
+
df = df.sample(frac=1, random_state=42).reset_index(drop=True)
|
| 76 |
+
|
| 77 |
+
print("=" * 70)
|
| 78 |
+
print(" SAMPLE DATASET CREATED")
|
| 79 |
+
print("=" * 70)
|
| 80 |
+
print(f" Shape: {df.shape}")
|
| 81 |
+
print(f" Columns: {list(df.columns)}")
|
| 82 |
+
print(f"\n First 5 rows:")
|
| 83 |
+
print(df.head().to_string())
|
| 84 |
+
|
| 85 |
+
return df
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# ==============================================================================
|
| 89 |
+
# PHẦN 2: Data Quality Assessment
|
| 90 |
+
# ==============================================================================
|
| 91 |
+
|
| 92 |
+
def assess_data_quality(df: pd.DataFrame):
|
| 93 |
+
"""Đánh giá chất lượng dữ liệu toàn diện."""
|
| 94 |
+
|
| 95 |
+
print("\n" + "=" * 70)
|
| 96 |
+
print(" DATA QUALITY ASSESSMENT")
|
| 97 |
+
print("=" * 70)
|
| 98 |
+
|
| 99 |
+
# 2.1 Missing Values
|
| 100 |
+
print("\n--- 1. Missing Values ---")
|
| 101 |
+
missing = df.isnull().sum()
|
| 102 |
+
missing_pct = (missing / len(df) * 100).round(2)
|
| 103 |
+
missing_report = pd.DataFrame({
|
| 104 |
+
'Missing Count': missing,
|
| 105 |
+
'Missing %': missing_pct,
|
| 106 |
+
'Data Type': df.dtypes
|
| 107 |
+
})
|
| 108 |
+
missing_report = missing_report[missing_report['Missing Count'] > 0].sort_values(
|
| 109 |
+
'Missing %', ascending=False
|
| 110 |
+
)
|
| 111 |
+
print(missing_report.to_string())
|
| 112 |
+
|
| 113 |
+
# 2.2 Duplicates
|
| 114 |
+
print("\n--- 2. Duplicates ---")
|
| 115 |
+
dup_count = df.duplicated().sum()
|
| 116 |
+
dup_id = df['order_id'].duplicated().sum()
|
| 117 |
+
print(f" Full row duplicates: {dup_count}")
|
| 118 |
+
print(f" Duplicate order_ids: {dup_id}")
|
| 119 |
+
|
| 120 |
+
# 2.3 Negative/Invalid Values
|
| 121 |
+
print("\n--- 3. Invalid Values ---")
|
| 122 |
+
numeric_cols = df.select_dtypes(include=[np.number]).columns
|
| 123 |
+
for col in numeric_cols:
|
| 124 |
+
neg_count = (df[col] < 0).sum()
|
| 125 |
+
zero_count = (df[col] == 0).sum()
|
| 126 |
+
if neg_count > 0 or (zero_count > 0 and col != 'review_score'):
|
| 127 |
+
print(f" {col}: {neg_count} negative, {zero_count} zeros")
|
| 128 |
+
|
| 129 |
+
# 2.4 Consistency check
|
| 130 |
+
print("\n--- 4. Consistency ---")
|
| 131 |
+
if 'order_status' in df.columns:
|
| 132 |
+
print(f" order_status unique values: {df['order_status'].unique()}")
|
| 133 |
+
print(f" → Inconsistency: mixed case (delivered, DELIVERED, Delivered)")
|
| 134 |
+
|
| 135 |
+
# 2.5 Outliers (IQR method)
|
| 136 |
+
print("\n--- 5. Outliers (IQR Method) ---")
|
| 137 |
+
for col in ['price', 'freight_value', 'delivery_days', 'product_weight_g']:
|
| 138 |
+
if col in df.columns:
|
| 139 |
+
data = df[col].dropna()
|
| 140 |
+
Q1 = data.quantile(0.25)
|
| 141 |
+
Q3 = data.quantile(0.75)
|
| 142 |
+
IQR = Q3 - Q1
|
| 143 |
+
lower = Q1 - 1.5 * IQR
|
| 144 |
+
upper = Q3 + 1.5 * IQR
|
| 145 |
+
outliers = ((data < lower) | (data > upper)).sum()
|
| 146 |
+
print(f" {col}: Q1={Q1:.1f}, Q3={Q3:.1f}, IQR={IQR:.1f}, "
|
| 147 |
+
f"bounds=[{lower:.1f}, {upper:.1f}], outliers={outliers} ({outliers/len(data)*100:.1f}%)")
|
| 148 |
+
|
| 149 |
+
# 2.6 Summary Score
|
| 150 |
+
print("\n--- 6. Quality Score ---")
|
| 151 |
+
total_cells = df.shape[0] * df.shape[1]
|
| 152 |
+
missing_cells = df.isnull().sum().sum()
|
| 153 |
+
completeness = (1 - missing_cells / total_cells) * 100
|
| 154 |
+
print(f" Completeness: {completeness:.1f}%")
|
| 155 |
+
print(f" Total issues found: missing={missing_cells}, duplicates={dup_count}")
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
# ==============================================================================
|
| 159 |
+
# PHẦN 3: Data Cleaning
|
| 160 |
+
# ==============================================================================
|
| 161 |
+
|
| 162 |
+
def clean_data(df: pd.DataFrame) -> pd.DataFrame:
|
| 163 |
+
"""Làm sạch dữ liệu."""
|
| 164 |
+
|
| 165 |
+
print("\n" + "=" * 70)
|
| 166 |
+
print(" DATA CLEANING")
|
| 167 |
+
print("=" * 70)
|
| 168 |
+
|
| 169 |
+
df_clean = df.copy()
|
| 170 |
+
original_shape = df_clean.shape
|
| 171 |
+
|
| 172 |
+
# 3.1 Standardize categorical values
|
| 173 |
+
print("\n--- Step 1: Standardize Categories ---")
|
| 174 |
+
if 'order_status' in df_clean.columns:
|
| 175 |
+
before = df_clean['order_status'].nunique()
|
| 176 |
+
df_clean['order_status'] = df_clean['order_status'].str.lower().str.strip()
|
| 177 |
+
after = df_clean['order_status'].nunique()
|
| 178 |
+
print(f" order_status: {before} → {after} unique values")
|
| 179 |
+
|
| 180 |
+
if 'customer_state' in df_clean.columns:
|
| 181 |
+
df_clean['customer_state'] = df_clean['customer_state'].str.upper().str.strip()
|
| 182 |
+
|
| 183 |
+
# 3.2 Handle invalid values
|
| 184 |
+
print("\n--- Step 2: Fix Invalid Values ---")
|
| 185 |
+
# Remove negative prices
|
| 186 |
+
neg_price = (df_clean['price'] < 0).sum()
|
| 187 |
+
df_clean.loc[df_clean['price'] < 0, 'price'] = np.nan
|
| 188 |
+
print(f" price: {neg_price} negative values → set to NaN")
|
| 189 |
+
|
| 190 |
+
# Remove negative freight
|
| 191 |
+
neg_freight = (df_clean['freight_value'] < 0).sum()
|
| 192 |
+
df_clean.loc[df_clean['freight_value'] < 0, 'freight_value'] = np.nan
|
| 193 |
+
print(f" freight_value: {neg_freight} negative values → set to NaN")
|
| 194 |
+
|
| 195 |
+
# Remove negative delivery_days
|
| 196 |
+
neg_delivery = (df_clean['delivery_days'] < 0).sum()
|
| 197 |
+
df_clean.loc[df_clean['delivery_days'] < 0, 'delivery_days'] = np.nan
|
| 198 |
+
print(f" delivery_days: {neg_delivery} negative values → set to NaN")
|
| 199 |
+
|
| 200 |
+
# 3.3 Handle missing values
|
| 201 |
+
print("\n--- Step 3: Impute Missing Values ---")
|
| 202 |
+
|
| 203 |
+
# Numerical: median imputation (robust to outliers)
|
| 204 |
+
for col in ['price', 'freight_value', 'product_weight_g', 'delivery_days']:
|
| 205 |
+
if col in df_clean.columns:
|
| 206 |
+
n_missing = df_clean[col].isna().sum()
|
| 207 |
+
median_val = df_clean[col].median()
|
| 208 |
+
df_clean[col].fillna(median_val, inplace=True)
|
| 209 |
+
print(f" {col}: {n_missing} missing → filled with median ({median_val:.2f})")
|
| 210 |
+
|
| 211 |
+
# Categorical: mode imputation
|
| 212 |
+
for col in ['customer_state']:
|
| 213 |
+
if col in df_clean.columns:
|
| 214 |
+
n_missing = df_clean[col].isna().sum()
|
| 215 |
+
mode_val = df_clean[col].mode()[0]
|
| 216 |
+
df_clean[col].fillna(mode_val, inplace=True)
|
| 217 |
+
print(f" {col}: {n_missing} missing → filled with mode ({mode_val})")
|
| 218 |
+
|
| 219 |
+
# review_score: forward fill or mode
|
| 220 |
+
if 'review_score' in df_clean.columns:
|
| 221 |
+
n_missing = df_clean['review_score'].isna().sum()
|
| 222 |
+
df_clean['review_score'].fillna(df_clean['review_score'].mode()[0], inplace=True)
|
| 223 |
+
print(f" review_score: {n_missing} missing → filled with mode")
|
| 224 |
+
|
| 225 |
+
# 3.4 Handle outliers (capping/winsorizing)
|
| 226 |
+
print("\n--- Step 4: Handle Outliers (Capping) ---")
|
| 227 |
+
for col in ['price', 'freight_value', 'delivery_days']:
|
| 228 |
+
if col in df_clean.columns:
|
| 229 |
+
Q1 = df_clean[col].quantile(0.01)
|
| 230 |
+
Q99 = df_clean[col].quantile(0.99)
|
| 231 |
+
before_outliers = ((df_clean[col] < Q1) | (df_clean[col] > Q99)).sum()
|
| 232 |
+
df_clean[col] = df_clean[col].clip(lower=Q1, upper=Q99)
|
| 233 |
+
print(f" {col}: Capped to [{Q1:.2f}, {Q99:.2f}], {before_outliers} values adjusted")
|
| 234 |
+
|
| 235 |
+
# 3.5 Remove duplicates
|
| 236 |
+
print("\n--- Step 5: Remove Duplicates ---")
|
| 237 |
+
before = len(df_clean)
|
| 238 |
+
df_clean = df_clean.drop_duplicates(subset=['order_id'])
|
| 239 |
+
after = len(df_clean)
|
| 240 |
+
print(f" Rows: {before} → {after} (removed {before - after} duplicates)")
|
| 241 |
+
|
| 242 |
+
print(f"\n Final shape: {original_shape} → {df_clean.shape}")
|
| 243 |
+
|
| 244 |
+
return df_clean
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
# ==============================================================================
|
| 248 |
+
# PHẦN 4: Normalization Comparison
|
| 249 |
+
# ==============================================================================
|
| 250 |
+
|
| 251 |
+
def normalize_comparison(df: pd.DataFrame):
|
| 252 |
+
"""So sánh các phương pháp normalization."""
|
| 253 |
+
|
| 254 |
+
print("\n" + "=" * 70)
|
| 255 |
+
print(" NORMALIZATION COMPARISON")
|
| 256 |
+
print("=" * 70)
|
| 257 |
+
|
| 258 |
+
col = 'price'
|
| 259 |
+
data = df[[col]].dropna().copy()
|
| 260 |
+
|
| 261 |
+
# Apply different scalers
|
| 262 |
+
scalers = {
|
| 263 |
+
'Original': data[col].values,
|
| 264 |
+
'Min-Max [0,1]': MinMaxScaler().fit_transform(data).flatten(),
|
| 265 |
+
'Z-Score (Standard)': StandardScaler().fit_transform(data).flatten(),
|
| 266 |
+
'Robust (IQR)': RobustScaler().fit_transform(data).flatten(),
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
+
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
|
| 270 |
+
|
| 271 |
+
for ax, (name, values) in zip(axes.flat, scalers.items()):
|
| 272 |
+
ax.hist(values, bins=50, alpha=0.7, color='#3498db', edgecolor='white')
|
| 273 |
+
ax.set_title(f'{name}\nmean={np.mean(values):.2f}, std={np.std(values):.2f}')
|
| 274 |
+
ax.set_ylabel('Frequency')
|
| 275 |
+
ax.axvline(np.mean(values), color='red', linestyle='--', label=f'Mean={np.mean(values):.2f}')
|
| 276 |
+
ax.axvline(np.median(values), color='green', linestyle='--', label=f'Median={np.median(values):.2f}')
|
| 277 |
+
ax.legend(fontsize=8)
|
| 278 |
+
|
| 279 |
+
plt.suptitle('Normalization Methods Comparison (price column)', fontsize=14, fontweight='bold')
|
| 280 |
+
plt.tight_layout()
|
| 281 |
+
plt.savefig('normalization_comparison.png', dpi=150, bbox_inches='tight')
|
| 282 |
+
print(f"\n [OK] Saved: normalization_comparison.png")
|
| 283 |
+
plt.close()
|
| 284 |
+
|
| 285 |
+
# Print statistics
|
| 286 |
+
print(f"\n Statistics comparison for '{col}':")
|
| 287 |
+
print(f" {'Method':<25} {'Mean':>10} {'Std':>10} {'Min':>10} {'Max':>10}")
|
| 288 |
+
print(f" {'-'*65}")
|
| 289 |
+
for name, values in scalers.items():
|
| 290 |
+
print(f" {name:<25} {np.mean(values):>10.3f} {np.std(values):>10.3f} "
|
| 291 |
+
f"{np.min(values):>10.3f} {np.max(values):>10.3f}")
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
# ==============================================================================
|
| 295 |
+
# PHẦN 5: PCA (Dimensionality Reduction)
|
| 296 |
+
# ==============================================================================
|
| 297 |
+
|
| 298 |
+
def pca_analysis(df: pd.DataFrame):
|
| 299 |
+
"""PCA analysis trên product dimensions."""
|
| 300 |
+
|
| 301 |
+
print("\n" + "=" * 70)
|
| 302 |
+
print(" PCA - DIMENSIONALITY REDUCTION")
|
| 303 |
+
print("=" * 70)
|
| 304 |
+
|
| 305 |
+
# Chọn features số
|
| 306 |
+
features = ['price', 'freight_value', 'product_weight_g',
|
| 307 |
+
'product_length_cm', 'product_height_cm', 'product_width_cm',
|
| 308 |
+
'delivery_days']
|
| 309 |
+
|
| 310 |
+
available_features = [f for f in features if f in df.columns]
|
| 311 |
+
data = df[available_features].dropna()
|
| 312 |
+
|
| 313 |
+
print(f" Features: {available_features}")
|
| 314 |
+
print(f" Samples: {len(data)}")
|
| 315 |
+
|
| 316 |
+
# Standardize
|
| 317 |
+
scaler = StandardScaler()
|
| 318 |
+
data_scaled = scaler.fit_transform(data)
|
| 319 |
+
|
| 320 |
+
# PCA
|
| 321 |
+
pca = PCA()
|
| 322 |
+
pca_result = pca.fit_transform(data_scaled)
|
| 323 |
+
|
| 324 |
+
# Explained variance
|
| 325 |
+
print(f"\n Explained Variance Ratio:")
|
| 326 |
+
cumulative = 0
|
| 327 |
+
for i, (var, cum_var) in enumerate(zip(
|
| 328 |
+
pca.explained_variance_ratio_,
|
| 329 |
+
np.cumsum(pca.explained_variance_ratio_)
|
| 330 |
+
)):
|
| 331 |
+
marker = " ← 95% reached" if cum_var >= 0.95 and cumulative < 0.95 else ""
|
| 332 |
+
print(f" PC{i+1}: {var:.4f} ({var*100:.1f}%) "
|
| 333 |
+
f"Cumulative: {cum_var:.4f} ({cum_var*100:.1f}%){marker}")
|
| 334 |
+
cumulative = cum_var
|
| 335 |
+
|
| 336 |
+
# Determine number of components for 95% variance
|
| 337 |
+
n_components_95 = np.argmax(np.cumsum(pca.explained_variance_ratio_) >= 0.95) + 1
|
| 338 |
+
print(f"\n → {n_components_95} components explain 95%+ variance "
|
| 339 |
+
f"(reduced from {len(available_features)} features)")
|
| 340 |
+
|
| 341 |
+
# Component loadings
|
| 342 |
+
print(f"\n Component Loadings (first 3 PCs):")
|
| 343 |
+
loadings = pd.DataFrame(
|
| 344 |
+
pca.components_[:3].T,
|
| 345 |
+
index=available_features,
|
| 346 |
+
columns=[f'PC{i+1}' for i in range(3)]
|
| 347 |
+
).round(3)
|
| 348 |
+
print(loadings.to_string())
|
| 349 |
+
|
| 350 |
+
# Visualization
|
| 351 |
+
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
|
| 352 |
+
|
| 353 |
+
# Scree plot
|
| 354 |
+
axes[0].bar(range(1, len(pca.explained_variance_ratio_) + 1),
|
| 355 |
+
pca.explained_variance_ratio_, alpha=0.7, color='#3498db', label='Individual')
|
| 356 |
+
axes[0].plot(range(1, len(pca.explained_variance_ratio_) + 1),
|
| 357 |
+
np.cumsum(pca.explained_variance_ratio_), 'ro-', label='Cumulative')
|
| 358 |
+
axes[0].axhline(y=0.95, color='green', linestyle='--', label='95% threshold')
|
| 359 |
+
axes[0].set_xlabel('Principal Component')
|
| 360 |
+
axes[0].set_ylabel('Explained Variance Ratio')
|
| 361 |
+
axes[0].set_title('PCA Scree Plot')
|
| 362 |
+
axes[0].legend()
|
| 363 |
+
|
| 364 |
+
# 2D scatter plot (PC1 vs PC2)
|
| 365 |
+
scatter = axes[1].scatter(pca_result[:, 0], pca_result[:, 1],
|
| 366 |
+
c=data['price'].values, cmap='viridis',
|
| 367 |
+
alpha=0.5, s=10)
|
| 368 |
+
axes[1].set_xlabel(f'PC1 ({pca.explained_variance_ratio_[0]*100:.1f}%)')
|
| 369 |
+
axes[1].set_ylabel(f'PC2 ({pca.explained_variance_ratio_[1]*100:.1f}%)')
|
| 370 |
+
axes[1].set_title('PCA: PC1 vs PC2 (colored by price)')
|
| 371 |
+
plt.colorbar(scatter, ax=axes[1], label='Price')
|
| 372 |
+
|
| 373 |
+
plt.tight_layout()
|
| 374 |
+
plt.savefig('pca_analysis.png', dpi=150, bbox_inches='tight')
|
| 375 |
+
print(f"\n [OK] Saved: pca_analysis.png")
|
| 376 |
+
plt.close()
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
# ==============================================================================
|
| 380 |
+
# PHẦN 6: Feature Engineering
|
| 381 |
+
# ==============================================================================
|
| 382 |
+
|
| 383 |
+
def feature_engineering(df: pd.DataFrame) -> pd.DataFrame:
|
| 384 |
+
"""Feature Engineering cho Olist dataset."""
|
| 385 |
+
|
| 386 |
+
print("\n" + "=" * 70)
|
| 387 |
+
print(" FEATURE ENGINEERING")
|
| 388 |
+
print("=" * 70)
|
| 389 |
+
|
| 390 |
+
df_feat = df.copy()
|
| 391 |
+
new_features = []
|
| 392 |
+
|
| 393 |
+
# 1. Price features
|
| 394 |
+
if 'price' in df_feat.columns and 'freight_value' in df_feat.columns:
|
| 395 |
+
df_feat['freight_ratio'] = (df_feat['freight_value'] / df_feat['price']).round(4)
|
| 396 |
+
df_feat['total_value'] = df_feat['price'] + df_feat['freight_value']
|
| 397 |
+
df_feat['is_free_shipping'] = (df_feat['freight_value'] == 0).astype(int)
|
| 398 |
+
new_features.extend(['freight_ratio', 'total_value', 'is_free_shipping'])
|
| 399 |
+
|
| 400 |
+
# 2. Price binning
|
| 401 |
+
if 'price' in df_feat.columns:
|
| 402 |
+
df_feat['price_category'] = pd.qcut(
|
| 403 |
+
df_feat['price'], q=5,
|
| 404 |
+
labels=['very_low', 'low', 'medium', 'high', 'very_high'],
|
| 405 |
+
duplicates='drop'
|
| 406 |
+
)
|
| 407 |
+
new_features.append('price_category')
|
| 408 |
+
|
| 409 |
+
# 3. Product size features
|
| 410 |
+
size_cols = ['product_length_cm', 'product_height_cm', 'product_width_cm']
|
| 411 |
+
if all(c in df_feat.columns for c in size_cols):
|
| 412 |
+
df_feat['product_volume'] = (
|
| 413 |
+
df_feat['product_length_cm'] *
|
| 414 |
+
df_feat['product_height_cm'] *
|
| 415 |
+
df_feat['product_width_cm']
|
| 416 |
+
)
|
| 417 |
+
new_features.append('product_volume')
|
| 418 |
+
|
| 419 |
+
if 'product_weight_g' in df_feat.columns:
|
| 420 |
+
df_feat['product_density'] = (
|
| 421 |
+
df_feat['product_weight_g'] / df_feat['product_volume'].replace(0, np.nan)
|
| 422 |
+
).round(4)
|
| 423 |
+
df_feat['is_heavy'] = (df_feat['product_weight_g'] > 5000).astype(int)
|
| 424 |
+
new_features.extend(['product_density', 'is_heavy'])
|
| 425 |
+
|
| 426 |
+
# 4. Delivery features
|
| 427 |
+
if 'delivery_days' in df_feat.columns:
|
| 428 |
+
df_feat['delivery_category'] = pd.cut(
|
| 429 |
+
df_feat['delivery_days'],
|
| 430 |
+
bins=[0, 3, 7, 14, 30, float('inf')],
|
| 431 |
+
labels=['express', 'fast', 'normal', 'slow', 'very_slow']
|
| 432 |
+
)
|
| 433 |
+
df_feat['is_late'] = (df_feat['delivery_days'] > 14).astype(int)
|
| 434 |
+
new_features.extend(['delivery_category', 'is_late'])
|
| 435 |
+
|
| 436 |
+
# 5. Review features
|
| 437 |
+
if 'review_score' in df_feat.columns:
|
| 438 |
+
df_feat['is_positive'] = (df_feat['review_score'] >= 4).astype(int)
|
| 439 |
+
df_feat['is_negative'] = (df_feat['review_score'] <= 2).astype(int)
|
| 440 |
+
new_features.extend(['is_positive', 'is_negative'])
|
| 441 |
+
|
| 442 |
+
# 6. State-based features
|
| 443 |
+
if 'customer_state' in df_feat.columns:
|
| 444 |
+
state_region = {
|
| 445 |
+
'SP': 'Southeast', 'RJ': 'Southeast', 'MG': 'Southeast', 'ES': 'Southeast',
|
| 446 |
+
'PR': 'South', 'SC': 'South', 'RS': 'South',
|
| 447 |
+
'BA': 'Northeast', 'PE': 'Northeast', 'CE': 'Northeast',
|
| 448 |
+
'DF': 'Central-West', 'GO': 'Central-West', 'MT': 'Central-West',
|
| 449 |
+
'AM': 'North', 'PA': 'North',
|
| 450 |
+
}
|
| 451 |
+
df_feat['region'] = df_feat['customer_state'].map(state_region).fillna('Other')
|
| 452 |
+
new_features.append('region')
|
| 453 |
+
|
| 454 |
+
print(f" New features created: {len(new_features)}")
|
| 455 |
+
for feat in new_features:
|
| 456 |
+
dtype = df_feat[feat].dtype
|
| 457 |
+
nunique = df_feat[feat].nunique()
|
| 458 |
+
sample = df_feat[feat].head(3).tolist()
|
| 459 |
+
print(f" {feat}: dtype={dtype}, unique={nunique}, sample={sample}")
|
| 460 |
+
|
| 461 |
+
print(f"\n Shape: {df.shape} → {df_feat.shape} (+{len(new_features)} features)")
|
| 462 |
+
|
| 463 |
+
return df_feat
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
# ==============================================================================
|
| 467 |
+
# MAIN
|
| 468 |
+
# ==============================================================================
|
| 469 |
+
|
| 470 |
+
if __name__ == '__main__':
|
| 471 |
+
print("=" * 70)
|
| 472 |
+
print(" LAB 4: DATA PREPROCESSING")
|
| 473 |
+
print(" BIM5021 - Nha kho du lieu va Tich hop")
|
| 474 |
+
print("=" * 70)
|
| 475 |
+
|
| 476 |
+
# 1. Create sample data
|
| 477 |
+
df = create_sample_olist()
|
| 478 |
+
|
| 479 |
+
# 2. Assess quality
|
| 480 |
+
assess_data_quality(df)
|
| 481 |
+
|
| 482 |
+
# 3. Clean data
|
| 483 |
+
df_clean = clean_data(df)
|
| 484 |
+
|
| 485 |
+
# 4. Normalize comparison
|
| 486 |
+
normalize_comparison(df_clean)
|
| 487 |
+
|
| 488 |
+
# 5. PCA
|
| 489 |
+
pca_analysis(df_clean)
|
| 490 |
+
|
| 491 |
+
# 6. Feature Engineering
|
| 492 |
+
df_features = feature_engineering(df_clean)
|
| 493 |
+
|
| 494 |
+
print("\n" + "=" * 70)
|
| 495 |
+
print(" HOAN THANH LAB 4!")
|
| 496 |
+
print(" Files: normalization_comparison.png, pca_analysis.png")
|
| 497 |
+
print("=" * 70)
|