1. Data Preprocessing
Training Dataset
เรียกว่า Feature Matrix เรียกว่า Label Vector
คือจำนวนของ Features คือจำนวนของ Datasets
Feature Engineering
สามารถแบ่งประเภทของ Features ได้สองแบบคือ
- Continuos numeric
- Categorical features
Data Preprocessing
เช่นการ
- Handling missing value (ค่าที่หายไป)
- ลบ Rows นั้นออก
- แทนด้วยค่าเฉลี่ย, ค่า
unknown, ค่าที่น่าจะใกล้เคียงที่สุด - แทนด้วยค่าที่พบมากที่สุด (Categorial)
- Outlier Detection / Removal (ค่าที่ไม่ปกติ)
- Visually: ด้วยการทำ Scatter Plot
- Statiscally: ใช้ 2 หรือ 3 เท่าของ Standard deviations (SD) จากค่าเฉลี่ย
- Scaling / Normalization (Data smoothing)
- แบ่งออกเป็นกลุ่มๆ แล้วเปลี่ยนค่าในกลุ่มเป็น ค่าเฉลี่ยน, boundaries, medians ของกลุ่ม
- Normalization
- Decimal Scaling หายไปที่ละ (เปลี่ยนจนกว่าค่าที่มากที่สุดหารด้วย จะ )
- Min-max normalization (Mapping)
- Z-score normalization (Standardization)
- Feature Selection
- Class imbalance
Hot-deck imputation (Closest-fit algorithm)
- แทนค่าที่หายไป ด้วยค่าที่ใกล้เคียงที่สุด
- ตัวอย่าง
| Subject | Age | Income | Gender | |
|---|---|---|---|---|
| 1 | 29 | $40,000 | M | |
| 2 | 45 | $36,000 | M | |
| 3 | 81 | M | ||
| 4 | 22 | $16,000 | ||
| 5 | 41 | $98,000 | M | |
| 6 | 33 | $60,000 | F | |
| 7 | 22 | $24,000 | F | |
| 8 | $81,000 | F | - | |
| 9 | 33 | $55,000 | F | |
| 10 | 45 | $80,000 | F |
ปัญหา Curse of Dimensionality
- เมื่อจำนวนของ Features เพิ่มขึ้นจะทำให้ข้อมูลเกิดการกระจาย (Thinly scattered)
- สามารถแก้ปัญหาได้ 2 แบบ
- Feature Selection: เลือกเฉพาะที่มีประโยชน์
- Feature Aggregation: รวมหลายๆ features เป็นอันเดียว
Pearson Correlation (Correlation coeffienct)
ไว้หาความสัมพันธ์ของตัวเลขสองตัวแปร
Mutual Information
- ไว้วัดความสัมพันธ์ระหว่าง Features กับ Label
- ค่า MI ที่สูง: สัมพันธ์กันสูง
- ค่า MI ที่ต่ำ: สัมพันธ์กันต่ำ
- ตัวอย่าง. จงคำนวนหาค่า MI ระหว่าง Outlook / Temperature


2. Distance-based Classification
Centroid-based Classification
- สร้าง Centroid (จุดศูนย์กลางของทุกจุดใน Class นั้นๆ)
-
จากนั้นดูว่าใกล้ Centroid ของอันไหนมากกว่ากัน
- ถ้า แสดงว่าเป็น Class
+, นอกนั้นเป็น Class-
- ถ้า แสดงว่าเป็น Class
-
ตัวอย่าง
Student Height Weight Label (Gender) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 = Female = Male
- ถ้ามีนักเรียนคนที่ 19 มา , จะได้ Gender อะไร?
K-NN Nearest Neightbor Classification
- ดูว่า
k(1, 2, 3, ...) จุดที่ใกล้ที่สุด เป็น Class อะไร (majority vote)
-
ตัวอย่าง
Petal Sepal Class ข้อมูลที่ต้องการทดสอบ
No Petal Sepal Class 1 5.4 2.9 ?? - ถ้า ค่าที่น้อยสุด 3 อันดับแรกคือ
- ,
- ,
- ,
- จะได้ เยอะที่สุด คำตอบจึงเป็น
- ถ้า ค่าที่น้อยสุด 3 อันดับแรกคือ
K-dimensional Tree (K-d Tree)
-
เป็นวิธีการเก็บข้อมูลสำหรับการหา Nearest Neighbor
-
โดยจะแบ่งเป็นหลายๆ มิติ
-
วิธ๊สร้าง
- นำข้อมูลมาเรียงด้วยแกน x
- แบ่งข้อมูลด้วยค่า Median
- กลับไปข้อ 1. ด้วยแกน y
-
วิธีใช้: คล้ายๆ กับ BST
-
ตัวอย่าง
X Y 7 2 5 9 9 6 4 7 8 1 7 6 เรียงด้วยแกน จะได้ค่า Median = , จากนั้นแบ่งข้อมูลด้วย กับ

ฝั่ง , เรียงด้วยแกน y จะได้ค่า Median = , จากนั้นแบ่งข้อมูลด้วย กับ

ฝั่ง , เรียงด้วยแกน y จะได้ค่า Median = , จากนั้นแบ่งข้อมูลด้วย กับ

💻 Code
- Centroid-based classification
from sklearn.neighbors import NearestCentroid- K-neighbors classification
from sklearn.neighbors import KNeighborsClassifier
model = KNeighborsClassifier(n_neighbors=5, algorithm='auto')
# algorithm = 'auto', 'kd_tree', 'brute'- Create random dataset
from sklearn.datasets import make_classification
X, y = make_classification(n_samples=1000,n_features=4,n_classes=2)- Train test split
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)- Hyper-parameter tuning (GridSearchCV)
from sklearn.model_selection import GridSearchCV
params = {'n_neighbors': list(range(1, 10))} # 'n_neighbors': [1, 2, 3, 4, 5, 6, 7, 8, 9]
clf = GridSearchCV(model, params)
clf.fit(X_train, y_train)
clf.best_params_
# {'n_neighbors': 9}
clf.best_estimator_
# เอา Model ที่ดีที่สุดออกมา- Saving / Import model
import pickle
pickle.dump(model, open('my_model.sav', 'wb'))
loaded_model = pickle.load(open('my_model.sav', 'rb'))3. Tree-based Classification
Decision Tree
ประกอบไปด้วย
- Internal Node: จุดที่จะตัดสินใจ (จาก Feature ใด Feature หนึ่ง)
- Branch (Edge/เส้น): ผลลัพท์ของการตัดสินใจ
- Left Node ผลลัพท์สุดท้าย (Label)

Entropy measurement (วัดค่าความไม่แน่นอน)
- เป็นการวัดค่าความสุ่ม ความไม่นอน
- คือ Labels, ข้อมูล row นึง
- โดยจะเลือกแบ่ง Decision Tree จากค่า Entropy ที่น้อยที่สุด
- ยิ่งค่ามาก จำนวนของแต่ละ Class จะเท่าๆ กัน
- ยิ่งค่าน้อย จำนวนของแต่ละ Class จะต่างกัน
- ตัวอย่าง

Gini Index
- เป็นการวัดค่าความไม่เท่าเทียม/ความบริสุทธ์ ของแต่ละ Class
- เลือกแบ่ง Decision Tree จากค่า Gini ที่น้อยที่สุด
- ถ้า หมายความว่ามี 1 Class เท่านั้น
- ถ้า หมายความว่าทุกๆ Class มีจำนวนเท่ากัน
- ตัวอย่าง

Information Gain
- สำหรับคำนวนว่าควรแบ่ง Decision Tree ตรงไหน
- จำนวน sample ที่อยู่ใน feature
- จำนวน sample
- ค่า Entropy ของ Label เมื่อถ้า
-
ตัวอย่าง
Name Hair Height Weight Lotion Result Sarah Blonde Average Light No Subburned Dana Blonde Tall Average Yes None Alex Brown Short Average Yes None Annie Blonde Short Average No Subburned Emily Red Average Heavy No Subburned Pete Brown Tall Heavy No None John Brown Average Heavy No None Katie Blonde Short Light Yes None - คำนวน Entropy ของ Label
- คำนวน Entropy ของ Label เมื่อแบ่ง Feature ด้วย Hair
Name Hair Height Weight Lotion Result Sarah Blonde Average Light No Subburned Dana Blonde Tall Average Yes None Annie Blonde Short Average No Subburned Katie Blonde Short Light Yes None Name Hair Height Weight Lotion Result Emily Red Average Heavy No Subburned Name Hair Height Weight Lotion Result Alex Brown Short Average Yes None Pete Brown Tall Heavy No None John Brown Average Heavy No None - ค่า Information Gain เมื่อแบ่งด้วย Hair จึงได้ (Blonde, Red, Brown ตามลำดับ)
- ค่า Information Gain เมื่อแบ่งด้วย Weight (Light, Average, Heavy)
- ค่า Information Gain เมื่อแบ่งด้วย Lotion (Yes, No)
- จากค่า IG เมื่อแบ่งด้วย Hair, Weight, Lotion จะได้ค่า IG สูงสุดเมื่อแบ่งด้วย Hair

Tree Ensemble
- การรวม Decision Tree หลายๆ อันมาช่วยตัดสินใจ
- สามารถทำได้ 2 แบบคือ
-
Bagging: แบ่ง Training data ออกเป็นหลายๆ แล้วเอาไปทำ Model เมื่อใช้งานก็จะให้ดูว่าคำตอบไหนเป็นคำตอบที่ตอบเยอะที่สุด
-
Boosting: สร้าง Decision Tree มาต่อๆ กัน เพื่อให้ Decision อันต่อมาแก้คำตอบของอันก่อนหน้า
- มักจะสร้าง Weak Tree ที่มีเพียง 1-2 ชั้น
- แต่จะเอาคำตอบของต้นแรก มาทำต้นต่อมาเพื่อลดข้อผิดพลาด
- เช่น XGBoost

-
💻 Code
- สร้าง Decision Tree
from sklearn.tree import DecisionTreeClassifier
model = DecisionTreeClassifier(max_depth=5, criterion='entropy')
model.fit(X_train, y_train)- ดูกราฟ Decision Tree
from sklearn.tree import plot_tree
import matplotlib.pyplot as plt
plt.figure(figsize=(20, 10))
tree.plot_tree(model, filled=True, features_names=X_train.columns, class_names=['<=50K', '>50K'])
plt.show()- เปลี่ยนข้อมูล Categorical แบบตัวอักษร หรืออื่นๆ ไปเป็น ตัวเลข (Label Encode)
from sklearn.preprocessing import LabelEncoder
label_encoder = LabelEncoder()
df['f1'] = label_encoder.fit_transform(df['f1'])- ทำ Random Forest (Tree Ensemble)
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=10, criterion='entropy', max_depth=5)
model.fit(X_train, y_train)- ดูกราฟ Random Forest
from sklearn.tree import plot_tree
import matplotlib.pyplot as plt
fig, axes = plt.subplot(nrows=1, ncols=3, figsize=(10, 2), dpi=900)
for idx in range(3):
plot_tree(model.estimators_[idx], filled=True,
feature_names=X_train.columns,
class_names=['<=50K', '>50K'],
ax=axes.ravel()[idx]
)- สร้าง XGBoost
import xgboost as xgb
model = xgb.XGBClassifier(objective='multi:softmax', n_estimators=10, max_depth=5, num_class=3)
mode.fit(X_train, X_test)