Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python - Feature Scaling: ทำไม ตอนไหน และอย่างไร

Feature Scaling เป็นขั้นตอน Data Pre-processing ที่นำไปใช้กับ independent variables (features) ช่วย normalize ข้อมูลให้อยู่ในช่วงที่กำหนด

ทำไมต้อง Scale? (Why Scaling?)

Dataset ส่วนใหญ่มี features ที่แตกต่างกันมากใน magnitude, units และ range แต่มากกว่าครึ่งของ ML algorithms ใช้ Euclidean distance ระหว่างจุดข้อมูล ซึ่งเป็นปัญหาเพราะ:

  • Algorithms ดูแค่ magnitude ไม่สน unit → 5kg vs 5000g ให้ผลต่างกัน
  • Features ที่ magnitude สูง จะ dominate distance calculations
  • ต้องนำ features ทุกตัวไปอยู่ระดับ magnitude เดียวกัน

วิธี Scale Features (How to Scale)

1. Standardization (Z-score Normalization)

$$x' = \frac{x - \bar{x}}{\sigma}$$

  • แจกแจงใหม่: mean μ = 0, std σ = 1
  • ใช้ sklearn.preprocessing.scale หรือ StandardScaler
  • เหมาะสำหรับ algorithms ที่สมมติ zero-centric data (PCA)

2. Mean Normalization

$$x' = \frac{x - mean(x)}{max(x) - min(x)}$$

  • ค่าอยู่ระหว่าง -1 ถึง 1, μ = 0
  • เหมาะสำหรับ PCA

3. Min-Max Scaling

$$x' = \frac{x - min(x)}{max(x) - min(x)}$$

  • ค่าอยู่ระหว่าง 0 ถึง 1
  • ใช้ MinMaxScaler
  • เหมาะเมื่อ features มี hard boundaries (เช่น pixel 0-255)

4. Unit Vector Scaling

$$x' = \frac{x}{\|x\|}$$

  • Scale ทั้ง feature vector ให้ความยาว = 1
  • เหมาะสำหรับ text classification (TF-IDF), cosine similarity

ตัวอย่างโค้ดกับ Scikit-learn


from sklearn.preprocessing import StandardScaler, MinMaxScaler, RobustScaler, Normalizer
import numpy as np

X = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])

# Standardization
scaler = StandardScaler()
X_std = scaler.fit_transform(X)
print("Standardized:\n", X_std)
print("Mean:", X_std.mean(axis=0), "Std:", X_std.std(axis=0))

# Min-Max Scaling
scaler = MinMaxScaler()
X_minmax = scaler.fit_transform(X)
print("Min-Max:\n", X_minmax)

# Robust Scaler (ใช้ median/IQR - ทน outlier)
scaler = RobustScaler()
X_robust = scaler.fit_transform(X)

# Unit Vector (Normalizer)
normalizer = Normalizer()
X_norm = normalizer.fit_transform(X)

เมื่อไหร่ควร Scale? (When to Scale)

Rule of thumb: Algorithm ที่คำนวณ distance หรือสมมติ normality → Scale features

Algorithmต้อง Scale?เหตุผล
k-NN, K-Means, SVM✅ ใช่ใช้ Euclidean distance
PCA✅ ใช่Variance ขึ้นกับ magnitude
Gradient Descent (LR, NN)✅ ใช่收敛 เร็วขึ้น, ไม่สั่น
Linear/Logistic RegressionแนะนำCoefficients ตีความง่ายขึ้น
Decision Trees, Random Forest❌ ไม่ไม่ใช้ distance, split แบบ threshold
XGBoost, LightGBM❌ ไม่Tree-based
Naive Bayes, LDA❌ ไม่จำเป็นจัดการได้โดย design

ข้อผิดพลาดที่พบบ่อย


# ❌ ผิด: Fit scaler บน test data
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.fit_transform(X_test)  # ผิด! ต้องใช้ transform เฉยๆ

# ✅ ถูกต้อง: Fit เฉพาะ train, transform ทั้งคู่
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)  # ใช้ parameter จาก train

สรุป

  • Scale ก่อน train สำหรับ distance-based algorithms
  • Standardization สำหรับ zero-centric (PCA, SVM)
  • Min-Max สำหรับ bounded features (images, neural nets)
  • RobustScaler เมื่อมี outliers
  • Fit scaler บน training data เท่านั้น!
  • Tree-based models ไม่ต้อง scale