Data Preprocessing เป็นขั้นตอนสำคัญใน ML Pipeline: ทำความสะอาดข้อมูล ลบ Noise จัดการ Missing Values แปลงข้อมูลให้เหมาะสมกับอัลกอริทึม
scikit-learn มีโมดูล sklearn.preprocessing สำหรับ Preprocessing หลากหลาย เช่น Scaling, Encoding, Imputation, Discretization, Binarization
ตัวอย่าง: Binarizer - แปลงตัวเลขเป็น Boolean (0/1)
import numpy as np
from sklearn import preprocessing
input_data = np.array([
[34.78, 31.9, -65.5],
[-16.5, 2.45, -83.5],
[0.5, -87.98, 45.62],
[5.9, 2.38, -55.82]
])
# Threshold = 0.5: ค่า > 0.5 → 1, ค่า ≤ 0.5 → 0
data_binarized = preprocessing.Binarizer(threshold=0.5).transform(input_data)
print("Values converted from numeric to Boolean :\n", data_binarized)
ผลลัพธ์
Values converted from numeric to Boolean :
[[1. 1. 0.]
[0. 1. 0.]
[0. 0. 1.]
[1. 1. 0.]]
คำอธิบาย
นำเข้า NumPy และ sklearn.preprocessing
สร้างข้อมูลตัวอย่าง 4x3
ใช้
Binarizer(threshold=0.5)แปลงค่า > 0.5 เป็น 1.0, ≤ 0.5 เป็น 0.0เรียก
.transform()เพื่อแปลงข้อมูล
Preprocessing Tools หลักใน sklearn.preprocessing
| Class/Function | วัตถุประสงค์ |
|---|---|
| StandardScaler | Standardization (Mean=0, Std=1) |
| MinMaxScaler | Normalization ไปยัง [0,1] |
| RobustScaler | Scaling ทนต่อ Outliers (ใช้ Median/IQR) |
| MaxAbsScaler | Scaling ด้วย Max Absolute Value |
| Binarizer | แปลงเป็น 0/1 ตาม Threshold |
| OneHotEncoder | Categorical → One-Hot Vectors |
| LabelEncoder | Categorical Labels → Integers |
| OrdinalEncoder | Ordinal Categorical → Integers |
| SimpleImputer | 填补 Missing Values (mean, median, mode) |
| KBinsDiscretizer | Continuous → Discrete Bins |
| PolynomialFeatures | สร้าง Polynomial Features |
Best Practice: ใช้ Pipeline
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
pipe = Pipeline([
('scaler', StandardScaler()),
('clf', LogisticRegression())
])
pipe.fit(X_train, y_train)
Pipeline ป้องกัน Data Leakage และทำให้ Workflow สะอาด ต่อเนื่อง