ml_mt_note

August 22, 2024

1. Data Preprocessing

Training Dataset

Xn={Xn1,Xn2,...,XnD}X_n = \{ X_{n1}, X_{n2}, ..., X_{nD} \} เรียกว่า Feature Matrix Y={y1,y2,...,yn}Y = \{ y_1, y_2, ..., y_n \} เรียกว่า Label Vector

DD คือจำนวนของ Features NN คือจำนวนของ Datasets

Feature Engineering

สามารถแบ่งประเภทของ Features ได้สองแบบคือ

  1. Continuos numeric
  2. Categorical features

Data Preprocessing

เช่นการ

  1. Handling missing value (ค่าที่หายไป)
    • ลบ Rows นั้นออก
    • แทนด้วยค่าเฉลี่ย, ค่า unknown, ค่าที่น่าจะใกล้เคียงที่สุด
    • แทนด้วยค่าที่พบมากที่สุด​ (Categorial)
  2. Outlier Detection / Removal (ค่าที่ไม่ปกติ)
    • Visually: ด้วยการทำ Scatter Plot
    • Statiscally: ใช้ 2 หรือ 3 เท่าของ Standard deviations (SD) จากค่าเฉลี่ย
    S.D.=(xixˉ)2n1S.D. = \sqrt{\sum{\dfrac{(x_i - \bar{x})^2}{n - 1}}}
  3. Scaling / Normalization (Data smoothing)
    • แบ่งออกเป็นกลุ่มๆ แล้วเปลี่ยนค่าในกลุ่มเป็น ค่าเฉลี่ยน, boundaries, medians ของกลุ่ม
    • Normalization
      • Decimal Scaling หายไปที่ละ 10j10^j (เปลี่ยนจนกว่าค่าที่มากที่สุดหารด้วย 10j10^j จะ 1\le 1)
    v=v10jv' = \dfrac{v}{10^j}
    • Min-max normalization (Mapping)
    v=vminoldmaxoldminold(maxnewminnew)+minnewv' = \dfrac{v - min_{old}}{max_{old} - min_{old}}(max_{new} - min_{new}) + min_{new}
    • Z-score normalization (Standardization) [3,3]\approx[3,-3]
    v=vvˉS.D.v' = \dfrac{v - \bar{v}}{S.D.}
  4. Feature Selection
  5. Class imbalance

Hot-deck imputation (Closest-fit algorithm)

  • แทนค่าที่หายไป ด้วยค่าที่ใกล้เคียงที่สุด
distance(x,y)=i=1ndistance(ai(x),ai(y))distance(ai(x),ai(y))={0,if ai(x)=ai(y)1,if ai(x)ai(y)disteud(ai(x),ai(y)),if ai(x) and ai(y) is numeric\begin{align} distance(x, y) & = \sum_{i=1}^{n} \color{red}{distance(a_i(x), a_i(y))} \\ \color{red}{distance(a_i(x), a_i(y))} & = \begin{cases} 0,& \text{if } a_i(x) = a_i(y)\\ 1,& \text{if } a_i(x) \neq a_i(y)\\ dist_{eud}(a_i(x), a_i(y)),& \text{if } a_i(x) \text{ and } a_i(y) \text{ is numeric}\\ \end{cases} \end{align}
  • ตัวอย่าง
SubjectAgeIncomeGenderdistance(ai(x),ai(8))distance(a_i(x), {\color{red}a_i(8)})
129$40,000M1+4000081000+1=410021 + \| 40000-81000 \| + 1 = 41002
245$36,000M1+3600081000+1=450001 + \| 36000-81000 \| + 1 = 45000
381M1+81000+1=810021 + \| 81000 \| + 1 = 81002
422$16,0001+1600081000+1=650021 + \| 16000-81000 \| + 1 = 65002
541$98,000M1+9800081000+1=170021 + \| 98000-81000 \| + 1 = 17002
633$60,000F1+6000081000+0=210011 + \| 60000-81000 \| + 0 = 21001
722$24,000F1+2400081000+0=570011 + \| 24000-81000 \| + 0 = 57001
845\color{blue}45$81,000F-
933$55,000F1+5500081000+0=260011 + \| 55000-81000 \| + 0 = 26001
1045$80,000F1+8000081000+0=10001\color{blue} 1 + \| 80000-81000 \| + 0 = 10001

ปัญหา Curse of Dimensionality

  • เมื่อจำนวนของ Features เพิ่มขึ้นจะทำให้ข้อมูลเกิดการกระจาย (Thinly scattered)
  • สามารถแก้ปัญหาได้ 2 แบบ
    • Feature Selection: เลือกเฉพาะที่มีประโยชน์
    • Feature Aggregation: รวมหลายๆ features เป็นอันเดียว

Pearson Correlation (Correlation coeffienct)

ไว้หาความสัมพันธ์ของตัวเลขสองตัวแปร

r=(XiXˉ)(YiYˉ)(XiXˉ)2(YiYˉ)2r = \dfrac{\sum(X_i - \bar{X})(Y_i - \bar{Y})}{\sqrt{\sum(X_i - \bar{X})^2\sum(Y_i - \bar{Y})^2}}

Mutual Information

  • ไว้วัดความสัมพันธ์ระหว่าง Features กับ Label
  • ค่า MI ที่สูง: สัมพันธ์กันสูง
  • ค่า MI ที่ต่ำ: สัมพันธ์กันต่ำ
I(X;Y)=yYxXp(x,y)log2(p(x,y)p(x)p(y))I(X;Y) = \sum_{y \in Y}\sum_{x \in X}p(x,y)log_2\left(\dfrac{p(x,y)}{p(x)p(y)}\right)
  • ตัวอย่าง. จงคำนวนหาค่า MI ระหว่าง Outlook / Temperature
MI Example
I(Outlook;Temperature)=yTemperaturexOutlookp(x,y)log2(p(x,y)p(x)p(y))=xOutlookp(x,Hot)log2(p(x,Hot)p(x)p(Hot))+xOutlookp(x,Cold)log2(p(x,Cold)p(x)p(Cold))+xOutlookp(x,Mild)log2(p(x,Mild)p(x)p(Mild))=[p(Sunny,Hot)log2(p(Sunny,Hot)p(Sunny)p(Hot))+p(Overcast,Hot)log2(p(Overcast,Hot)p(Overcast)p(Hot))+p(Rainy,Hot)log2(p(Rainy,Hot)p(Rainy)p(Hot))]+[p(Sunny,Cold)log2(p(Sunny,Cold)p(Sunny)p(Cold))+p(Overcast,Cold)log2(p(Overcast,Cold)p(Overcast)p(Cold))+p(Rainy,Cold)log2(p(Rainy,Cold)p(Rainy)p(Cold))]+[p(Sunny,Mild)log2(p(Sunny,Mild)p(Sunny)p(Mild))+p(Overcast,Mild)log2(p(Overcast,Mild)p(Overcast)p(Mild))+p(Rainy,Mild)log2(p(Rainy,Mild)p(Rainy)p(Mild))]\begin{align} I(\text{Outlook};\text{Temperature}) = & \sum_{y \in \text{Temperature}}\sum_{x \in \text{Outlook}}p(x,y)log_2\left(\dfrac{p(x,y)}{p(x)p(y)}\right) \\ = & \sum_{x \in \text{Outlook}}p(x,\text{\color{red}Hot})log_2\left(\dfrac{p(x,\text{\color{red}Hot})}{p(x)p(\text{\color{red}Hot})}\right) + \\ & \sum_{x \in \text{Outlook}}p(x,\text{\color{green}Cold})log_2\left(\dfrac{p(x,\text{\color{green}Cold})}{p(x)p(\text{\color{green}Cold})}\right) + \\ & \sum_{x \in \text{Outlook}}p(x,\text{\color{blue}Mild})log_2\left(\dfrac{p(x,\text{\color{blue}Mild})}{p(x)p(\text{\color{blue}Mild})}\right) \\ = & \left[ p(\text{\color{orange}Sunny},\text{\color{red}Hot})log_2\left(\dfrac{p(\text{\color{orange}Sunny},\text{\color{red}Hot})}{p(\text{\color{orange}Sunny})p(\text{\color{red}Hot})}\right) + p(\text{\color{purple}Overcast},\text{\color{red}Hot})log_2\left(\dfrac{p(\text{\color{purple}Overcast},\text{\color{red}Hot})}{p(\text{\color{purple}Overcast})p(\text{\color{red}Hot})}\right) + p(\text{\color{lime}Rainy},\text{\color{red}Hot})log_2\left(\dfrac{p(\text{\color{lime}Rainy},\text{\color{red}Hot})}{p(\text{\color{lime}Rainy})p(\text{\color{red}Hot})}\right) \right] + \\ & \left[ p(\text{\color{orange}Sunny},\text{\color{green}Cold})log_2\left(\dfrac{p(\text{\color{orange}Sunny},\text{\color{green}Cold})}{p(\text{\color{orange}Sunny})p(\text{\color{green}Cold})}\right) + p(\text{\color{purple}Overcast},\text{\color{green}Cold})log_2\left(\dfrac{p(\text{\color{purple}Overcast},\text{\color{green}Cold})}{p(\text{\color{purple}Overcast})p(\text{\color{green}Cold})}\right) + p(\text{\color{lime}Rainy},\text{\color{green}Cold})log_2\left(\dfrac{p(\text{\color{lime}Rainy},\text{\color{green}Cold})}{p(\text{\color{lime}Rainy})p(\text{\color{green}Cold})}\right) \right] + \\ & \left[ p(\text{\color{orange}Sunny},\text{\color{blue}Mild})log_2\left(\dfrac{p(\text{\color{orange}Sunny},\text{\color{blue}Mild})}{p(\text{\color{orange}Sunny})p(\text{\color{blue}Mild})}\right) + p(\text{\color{purple}Overcast},\text{\color{blue}Mild})log_2\left(\dfrac{p(\text{\color{purple}Overcast},\text{\color{blue}Mild})}{p(\text{\color{purple}Overcast})p(\text{\color{blue}Mild})}\right) + p(\text{\color{lime}Rainy},\text{\color{blue}Mild})log_2\left(\dfrac{p(\text{\color{lime}Rainy},\text{\color{blue}Mild})}{p(\text{\color{lime}Rainy})p(\text{\color{blue}Mild})}\right) \right] \end{align}
MI Example Answers

2. Distance-based Classification

Centroid-based Classification

  • สร้าง Centroid (จุดศูนย์กลางของทุกจุดใน Class นั้นๆ)
μ=1Nyn=1xnμ+=1N+yn=+1xn\begin{align} \mu_{-} & = \dfrac{1}{N_{-}} \sum_{y_n = -1} x_n \\ \mu_{+} & = \dfrac{1}{N_{+}} \sum_{y_n = +1} x_n \end{align}
  • จากนั้นดูว่าใกล้ Centroid ของอันไหนมากกว่ากัน

    f(x):=μx2μ+x2f(x) := ||\mu_{-} - x||^2 - ||\mu_{+} - x||^2
    • ถ้า f(x)0f(x) \ge 0 แสดงว่าเป็น Class +, นอกนั้นเป็น Class -
  • ตัวอย่าง

    StudentHeightWeightLabel (Gender)
    1100.0100.020.020.01\color{red}{-1}
    2100.0100.026.026.01\color{green}{1}
    3100.0100.030.430.41\color{green}{1}
    4100.0100.032.432.41\color{green}{1}
    5101.6101.627.027.01\color{green}{1}
    6101.6101.632.032.01\color{green}{1}
    7102.0102.021.021.01\color{red}{-1}
    8103.6103.629.629.61\color{green}{1}
    9104.4104.430.430.41\color{green}{1}
    10104.9104.922.022.01\color{red}{-1}
    11105.2105.220.020.01\color{red}{-1}
    12105.6105.634.434.41\color{green}{1}
    13107.2107.232.432.41\color{green}{1}
    14109.9109.934.934.91\color{green}{1}
    15111.0111.025.425.41\color{red}{-1}
    16114.2114.223.523.51\color{red}{-1}
    17115.5115.536.336.31\color{green}{1}
    18117.8117.826.926.91\color{red}{-1}

    1\color{red}-1 = Female 1\color{green}1 = Male

    Centroid of 1; Weight=100+102+104.9+105.2+111+114.2+117.87=107.871Height=20+21+22+20+25.4+23.5+26.97=22.685Centroid of 1; Weight=100+100+100+101.6+101.6+103.6+104.4+105.6+107.2+109.9+115.511=104.490Height=26.0+30.4+32.4+27.0+32.0+29.6+30.4+34.4+32.4+34.9+36.311=31.436\begin{align} \text{Centroid of } {-1}; \text{ Weight} & = \dfrac{100+102+104.9+105.2+111+114.2+117.8}{7} \\ & = {\color{red}107.871} \\ \text{Height} & = \dfrac{20+21+22+20+25.4+23.5+26.9}{7} \\ & = {\color{red}22.685} \\ \text{Centroid of } {1}; \text{ Weight} & = \dfrac{100+100+100+101.6+101.6+103.6+104.4+105.6+107.2+109.9+115.5}{11} \\ & = {\color{green}104.490} \\ \text{Height} & = \dfrac{26.0+30.4+32.4+27.0+32.0+29.6+30.4+34.4+32.4+34.9+36.3}{11} \\ & = {\color{green}31.436} \end{align}
    • ถ้ามีนักเรียนคนที่ 19 มา Height=120\text{Height} = 120, Weight=28.7\text{Weight} = 28.7 จะได้ Gender อะไร?
    distance(1,x)=(120107.871)2+(28.722.685)2=13.538distance(1,x)=(120104.490)2+(28.731.436)2=15.749\begin{align} distance({\color{red}-1},x) & = \sqrt{(120-{\color{red}107.871})^2 + (28.7-{\color{red}22.685})^2} \\ & = {\color{red}13.538} \\ distance({\color{green}1},x) & = \sqrt{(120-{\color{green}104.490})^2 + (28.7-{\color{green}31.436})^2} \\ & = {\color{green}15.749} \end{align}
    • Gender=Female\therefore \text{Gender} = \text{\color{red}Female}

K-NN Nearest Neightbor Classification

  • ดูว่า k (1, 2, 3, ...) จุดที่ใกล้ที่สุด เป็น Class อะไร (majority vote)
D(X,Y)=i=1D(xiyi)2D(X,Y) = \sqrt{\sum^D_{i=1}(x_i - y_i)^2}
  • ตัวอย่าง

    PetalSepalClassD(curr,1)D(curr, 1)
    4.94.93.03.0Setosa\text{\color{red}Setosa}(4.95.4)2+(3.02.9)2=0.509\sqrt{(4.9-{\color{blue}5.4})^2 + (3.0-{\color{blue}2.9})^2}={\color{red}0.509}
    4.74.73.23.2Setosa\text{\color{red}Setosa}(4.75.4)2+(3.22.9)2=0.761\sqrt{(4.7-{\color{blue}5.4})^2 + (3.2-{\color{blue}2.9})^2}={\color{red}0.761}
    4.64.63.13.1Setosa\text{\color{red}Setosa}(4.65.4)2+(3.12.9)2=0.824\sqrt{(4.6-{\color{blue}5.4})^2 + (3.1-{\color{blue}2.9})^2}=0.824
    5.05.03.63.6Setosa\text{\color{red}Setosa}(5.05.4)2+(3.62.9)2=0.806\sqrt{(5.0-{\color{blue}5.4})^2 + (3.6-{\color{blue}2.9})^2}=0.806
    6.46.43.23.2Versicolor\text{\color{green}Versicolor}(6.45.4)2+(3.22.9)2=1.044\sqrt{(6.4-{\color{blue}5.4})^2 + (3.2-{\color{blue}2.9})^2}=1.044
    6.96.93.13.1Versicolor\text{\color{green}Versicolor}(6.95.4)2+(3.12.9)2=1.513\sqrt{(6.9-{\color{blue}5.4})^2 + (3.1-{\color{blue}2.9})^2}=1.513
    5.55.52.32.3Versicolor\text{\color{green}Versicolor}(5.55.4)2+(2.32.9)2=0.608\sqrt{(5.5-{\color{blue}5.4})^2 + (2.3-{\color{blue}2.9})^2}={\color{red}0.608}
    6.56.52.82.8Versicolor\text{\color{green}Versicolor}(6.55.4)2+(2.82.9)2=1.104\sqrt{(6.5-{\color{blue}5.4})^2 + (2.8-{\color{blue}2.9})^2}=1.104
    6.76.73.03.0Virginica\text{\color{blue}Virginica}(6.75.4)2+(3.02.9)2=1.303\sqrt{(6.7-{\color{blue}5.4})^2 + (3.0-{\color{blue}2.9})^2}=1.303
    6.36.32.62.6Virginica\text{\color{blue}Virginica}(6.35.4)2+(2.62.9)2=0.948\sqrt{(6.3-{\color{blue}5.4})^2 + (2.6-{\color{blue}2.9})^2}=0.948
    6.56.53.03.0Virginica\text{\color{blue}Virginica}(6.55.4)2+(3.02.9)2=1.104\sqrt{(6.5-{\color{blue}5.4})^2 + (3.0-{\color{blue}2.9})^2}=1.104

    ข้อมูลที่ต้องการทดสอบ

    NoPetalSepalClass
    15.42.9??
    • ถ้า k=3k = 3 ค่าที่น้อยสุด 3 อันดับแรกคือ
      • 0.5090.509, Setosa\text{\color{red}Setosa}
      • 0.6080.608, Versicolor\text{\color{green}Versicolor}
      • 0.7610.761, Setosa\text{\color{red}Setosa}
    • จะได้ Setosa\text{\color{red}Setosa} เยอะที่สุด คำตอบจึงเป็น Setosa\text{\color{red}Setosa}

K-dimensional Tree (K-d Tree)

  • เป็นวิธีการเก็บข้อมูลสำหรับการหา Nearest Neighbor

  • โดยจะแบ่งเป็นหลายๆ มิติ

  • วิธ๊สร้าง

    1. นำข้อมูลมาเรียงด้วยแกน x
    2. แบ่งข้อมูลด้วยค่า Median
    3. กลับไปข้อ 1. ด้วยแกน y
  • วิธีใช้: คล้ายๆ กับ BST

  • ตัวอย่าง

    XY
    72
    59
    96
    47
    81
    76

    (7,2),(5,9),(9,6),(4,7),(8,1),(7,6)(7,2), (5,9), (9,6), (4,7), (8,1), (7,6) เรียงด้วยแกน xx (4,7),(5,9),(7,2),(7,6),(8,1),(9,6)({\color{red}4},7), ({\color{red}5},9), ({\color{red}7},2), ({\color{red}7},6), ({\color{red}8},1), ({\color{red}9},6) จะได้ค่า Median = 77, จากนั้นแบ่งข้อมูลด้วย <7\lt 7 กับ 7\ge 7

    K-d Tree step 1

    ฝั่ง <7\lt 7, (4,7),(5,9)(4,7),(5,9) เรียงด้วยแกน y (4,7),(5,9)(4,{\color{blue}7}),(5,{\color{blue}9}) จะได้ค่า Median = 88, จากนั้นแบ่งข้อมูลด้วย <8\lt 8 กับ 8\ge 8

    K-d Tree step 2

    ฝั่ง 7\ge 7, (8,1),(7,2),(7,6),(9,6)(8,{\color{blue}1}),(7,{\color{blue}2}),(7,{\color{blue}6}),(9,{\color{blue}6}) เรียงด้วยแกน y (8,1),(7,2),(7,6),(9,6)(8,{\color{blue}1}),(7,{\color{blue}2}),(7,{\color{blue}6}),(9,{\color{blue}6}) จะได้ค่า Median = 44, จากนั้นแบ่งข้อมูลด้วย <4\lt 4 กับ 4\ge 4

    K-d Tree step 3

💻 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)
Decision Tree

Entropy measurement (วัดค่าความไม่แน่นอน)

  • เป็นการวัดค่าความสุ่ม ความไม่นอน
  • H(S)[0,1]H(S) \in [0, 1]
  • CC คือ Labels, SS ข้อมูล row นึง
H(S)=cCpclog2(pc)H(S) = -\sum_{c \in C} p_c \cdot log_2 \left( p_c \right)
  • โดยจะเลือกแบ่ง Decision Tree จากค่า Entropy ที่น้อยที่สุด
    • ยิ่งค่ามาก จำนวนของแต่ละ Class จะเท่าๆ กัน
    • ยิ่งค่าน้อย จำนวนของแต่ละ Class จะต่างกัน
  • ตัวอย่าง
Entropy Measurement Example

Gini Index

  • เป็นการวัดค่าความไม่เท่าเทียม/ความบริสุทธ์ ของแต่ละ Class
  • Gini(S)[0,0.5]Gini(S) \in [0, 0.5]
  • เลือกแบ่ง Decision Tree จากค่า Gini ที่น้อยที่สุด
    • ถ้า Gini(S)=0Gini(S) = 0 หมายความว่ามี 1 Class เท่านั้น
    • ถ้า Gini(S)=0.5Gini(S) = 0.5 หมายความว่าทุกๆ Class มีจำนวนเท่ากัน
Gini(S)=1cCPc2Gini(S) = 1 - \sum_{c \in C}P_c^2
  • ตัวอย่าง
Geni Index Example

Information Gain

  • สำหรับคำนวนว่าควรแบ่ง Decision Tree ตรงไหน
  • Sf|S_f| จำนวน sample ที่อยู่ใน feature ff
  • S|S| จำนวน sample
  • H(Sf)H(S_f) ค่า Entropy ของ Label เมื่อถ้า
IG(S,F)=H(S)fFSfSH(Sf)IG(S,F) = H(S) - \sum_{f \in F} \dfrac{| S_f |}{| S |}H(S_f)
  • ตัวอย่าง

    NameHairHeightWeightLotionResult
    SarahBlondeAverageLightNoSubburned
    DanaBlondeTallAverageYesNone
    AlexBrownShortAverageYesNone
    AnnieBlondeShortAverageNoSubburned
    EmilyRedAverageHeavyNoSubburned
    PeteBrownTallHeavyNoNone
    JohnBrownAverageHeavyNoNone
    KatieBlondeShortLightYesNone
    • คำนวน Entropy ของ Label
    H(Result)=[P(Subburned)log2(Subburned)+P(None)log2(None)]=[(38)log2(38)+(58)log2(58)]=0.9544340029\begin{align} H(\text{Result}) & = - \left[P(\text{\color{red}Subburned})log2(\text{\color{red}Subburned}) + P(\text{\color{blue}None})log2(\text{\color{blue}None})\right] \\ & = - \left[ {\color{red}(\dfrac{3}{8})log2(\dfrac{3}{8})} + {\color{blue}(\dfrac{5}{8})log2(\dfrac{5}{8})} \right] \\ & = 0.9544340029 \end{align}
    • คำนวน Entropy ของ Label เมื่อแบ่ง Feature ด้วย Hair
    NameHairHeightWeightLotionResult
    SarahBlondeAverageLightNoSubburned
    DanaBlondeTallAverageYesNone
    AnnieBlondeShortAverageNoSubburned
    KatieBlondeShortLightYesNone
    H(TextHair="Blonde")=[P(Subburned)log2(Subburned)+P(None)log2(None)]=((24)log2(24)+(24)log2(24))=1\begin{align} H(\text{Text}|\text{Hair}="Blonde") & = - \left[P(\text{\color{red}Subburned})log2(\text{\color{red}Subburned}) + P(\text{\color{blue}None})log2(\text{\color{blue}None})\right] \\ & = - \left( {\color{red}(\dfrac{2}{4})log_2(\dfrac{2}{4})} + {\color{blue}(\dfrac{2}{4})log_2(\dfrac{2}{4})} \right) \\ & = 1 \end{align}
    NameHairHeightWeightLotionResult
    EmilyRedAverageHeavyNoSubburned
    H(TextHair="Red")=[P(Subburned)log2(Subburned)+P(None)log2(None)]=((11)log2(11)+(01)log2(01))=0\begin{align} H(\text{Text}|\text{Hair}="Red") & = - \left[P(\text{\color{red}Subburned})log2(\text{\color{red}Subburned}) + P(\text{\color{blue}None})log2(\text{\color{blue}None})\right] \\ & = - \left( {\color{red}(\dfrac{1}{1})log_2(\dfrac{1}{1})} + {\color{blue}(\dfrac{0}{1})log_2(\dfrac{0}{1})} \right) \\ & = 0 \end{align}
    NameHairHeightWeightLotionResult
    AlexBrownShortAverageYesNone
    PeteBrownTallHeavyNoNone
    JohnBrownAverageHeavyNoNone
    H(TextHair="Brown")=[P(Subburned)log2(Subburned)+P(None)log2(None)]=((03)log2(03)+(33)log2(33))=0\begin{align} H(\text{Text}|\text{Hair}="Brown") & = - \left[P(\text{\color{red}Subburned})log2(\text{\color{red}Subburned}) + P(\text{\color{blue}None})log2(\text{\color{blue}None})\right] \\ & = - \left( {\color{red}(\dfrac{0}{3})log_2(\dfrac{0}{3})} + {\color{blue}(\dfrac{3}{3})log_2(\dfrac{3}{3})} \right) \\ & = 0 \end{align}
    • ค่า Information Gain เมื่อแบ่งด้วย Hair จึงได้ (Blonde, Red, Brown ตามลำดับ)
    IG(Hair)=H(Result)[SBlondeSH(Blonde)+SRedSH(Red)+SBrownSH(Brown)]=0.954[48(1)+18(0)+38(0)]=0.454\begin{align} IG(\text{Hair}) & = H(\text{Result}) - \left[ \dfrac{|S_{Blonde}|}{|S|}H(Blonde) + \dfrac{|S_{Red}|}{|S|}H(Red) + \dfrac{|S_{Brown}|}{|S|}H(Brown) \right] \\ & = 0.954 - \left[ \dfrac{4}{8}(1) + \dfrac{1}{8}(0) + \dfrac{3}{8}(0) \right] \\ & = 0.454 \end{align}
    • ค่า Information Gain เมื่อแบ่งด้วย Weight (Light, Average, Heavy)
    IG(Weight)=0.964[28(1)+38(0.9182958341)+38(0.9182958341)]=0.015\begin{align} IG(\text{Weight}) & = 0.964 - \left[ \dfrac{2}{8}(1) + \dfrac{3}{8}(0.9182958341) + \dfrac{3}{8}(0.9182958341) \right] \\ & = 0.015 \end{align}
    • ค่า Information Gain เมื่อแบ่งด้วย Lotion (Yes, No)
    IG(Lotion)=0.964[38(0)+58(0.9709505945)]=0.347\begin{align} IG(\text{Lotion}) & = 0.964 - \left[ \dfrac{3}{8}(0) + \dfrac{5}{8}(0.9709505945) \right] \\ & = 0.347 \end{align}
    • \therefore จากค่า IG เมื่อแบ่งด้วย Hair, Weight, Lotion จะได้ค่า IG สูงสุดเมื่อแบ่งด้วย Hair
    Decision Tree Example

Tree Ensemble

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

    • Boosting: สร้าง Decision Tree มาต่อๆ กัน เพื่อให้ Decision อันต่อมาแก้คำตอบของอันก่อนหน้า

      • มักจะสร้าง Weak Tree ที่มีเพียง 1-2 ชั้น
      • แต่จะเอาคำตอบของต้นแรก มาทำต้นต่อมาเพื่อลดข้อผิดพลาด
      • เช่น XGBoost
      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)