1st Basic Data Science Project: Titanic Part#4.2 Deep Learning

Panuwat Ulis
Nov 2 · 5 min read

Deep learning หรืออีกชื่อที่เราคุ้นหูคือ Artificial Neural Network (ANN) เป็น machine learning ที่เลียนแบบการทำงานของสมองมนุษย์ ซึ่งสมองคนเราสามารถที่จะคิดและตัดสินใจปัญหาที่มีความสลับซับซ้อนได้ จุดนี้จึงเป็นแรงบันดาลใจทำให้เกิด ANN เพื่อที่จะมาแก้ไขปัญหาที่มีความซับซ้อนมากขึ้น โดยองค์ประกอบสำคัญใน ANN ก็คือ Perceptron

Perceptron

รูปแบบที่ง่ายที่สุดของ ANN ที่มีแค่ single neuron network โดยจะมีความคล้ายคลึงกับ neuron ทางชีวภาพ คือมีส่วนของ Dendrites ที่รับเอา input data จาก neuron อื่น แปลงผลผ่าน axon ส่งผ่านไปยัง axon terminals ยัง neuron ถัดไป ซึ่งตัว ANN ที่เป็น single layer ก็จะมีส่วนประกอบดังนี้

  1. Input data จะเป็น Feature ต่างๆจากข้อมูล จะถูกให้น้ำหนัก (Weight) ในแต่ละ Feature ไม่เท่ากัน
  2. Weight sum ค่า input กับ weight จะเข้าสู่กระบวนการ matric multiplication แล้วคิดผลรวมออกมา
  3. ผลรวมที่ได้จะถูกส่งไปที่ Activation Function เพื่อแปลงค่าออกเป็น output

ซึ่ง Single Layer Perceptron มันไม่สามารถแก้ปัญหาที่ซับซ้อนแบบ non-linear ได้ การที่จะแก้ปัญหานี้ได้ต้องทำเป็น Multi Layer Perceptron (MLP) โดย Jason Brownlee จาก blog machine learning mastery ได้นำเสนอ paper ของ Lippmann “An introduction to computing with neural nets” ว่าตัว MLP มีเพียง 2 hidden layers ก็เพียงพอต่อการแก้ปัญหา Classification ในรูปแบบต่างๆแล้ว

คำว่า “2 Layers MLP มันหมายถึง 1 input layer+1 hidden layer+ 1 output layer”

Multilayer Perceptron (MLP) ประกอบไปด้วย 3 ส่วนหลัก

  1. Input Layer รับค่า input variable
  2. Hidden Layer เป็น Layer ระหว่าง input กับ output ซึ่งจะมีมากกว่า 1 layer ก็ได้
  3. Output Layer เป็น Layer สุดท้ายในการแปลผลตามที่เราต้องการฃ

ในแต่ละ Layer ก็จะมี Activation function เป็นของตัวเอง และในแต่ละ Layer ก็จะประกอบไปด้วยหลาย Nodes

คำถามถัดมา แล้วถ้าจะเริ่มทำ MLP มันต้องมีกี่ layer มันต้องมีกี่ node หละ คำตอบคือ “ไม่รู้ “ เราอาจจะต้องทำการทดลองเองว่าใช้จำนวนกี่ Layer ในแต่ละ Layer มีกี่ node เพราะมันไม่ดีสูตรตายตัว จำนวน Layer กับ node เท่าไรนั้นมันก็จะเหมาะกับชุดข้อมูลนั้นๆ เราอาจจะหางานวิจัยของชาวบ้านที่มีความใกล้เคียงกันแล้วยืมไอเดียของเค้ามาทดสอบดู หรือทำการทดลองเองโดยใช้ Grid Search หรือ Random Search ในการหาจำนวนที่เหมาะสม

Activation Function

เป็น Function ที่แปลผลข้อมูลแล้วสร้างออกไปเป็น output โดยเราจะ focus ไปที่ non-linear activation function ซึ่งจะมีด้วยกัน 7 function

  • Sigmoid/Logistic
  • TanH/Hyperbolic Tangent
  • ReLu(Rectified Linear Unit)
  • Leaky ReLu
  • Parametric ReLu
  • Softmax
  • Swish

ซึ่งใน project นี้เราจะใช้ ReLu สำหรับ input และ hidden layer ส่วน output ที่เราทำ binary classification จะใช้ Sigmoid เพื่อให้ผลออกมาเป็น 0 กับ 1

หลักการทำงานของ MLP

เมื่อมีการใส่ input เข้ามาแล้วจะมีการ Random weight ที่จะให้กับ input แต่ละตัว หลังจากนั้นจะทำ Matric Multiplication แล้วมีการใส่ Bias ส่งเข้าสู่ Activation Function แล้วแปลงเป็น output ออกมา เมื่อได้ output ก็จะทำการไปเปรียบเทียบกับ actual value (label) ของข้อมูล แล้วทำการ Backpropagation เพื่อทำการคำนวณ Weight ใหม่จาก Error ที่เกิดขึ้นระหว่าง Output กับ Actual Value จนได้ Error ที่เกิดขึ้นต่างกันน้อยที่สุด โดยในการรัน ANN เราต้องกำหนดจำนวนรอบในการทำ Backpropagation นั้นคือ Epochs และ Batch_Size โดยจะกำหนดค่าเท่าไรนั้น ก็ต้องทำการ Trial /Error ว่าทำแค่ไหนถึงจะทำให้ Loss Function ลดลงเหลือน้อยที่สุด เพราะการรันที่เยอะขึ้นบางครั้งก็ไม่ได้ทำให้ผลออกมาดีขึ้น เช่นเดียวกับการเลือกจำนวน Layer และ Nodes

หลังจากเราเรียนรู้ Concept ของ MLP กันอย่างคร่าวๆแล้ว เรามาดูส่วนของการ Coding กันเลย โดยเริ่มต้นเราต้องทำข้อมูลของเราให้อยู่ในรูปของ Numeric ให้หมดเสียก่อนโดยการแปลง attribute ของเราที่เป็น Category ให้เป็น Numeric ด้วยการสร้าง Dummy Variable ขึ้นมา

Data Cleaning/Data Wrangling

drop attribute ที่ไม่สำคัญออกจาก data set เรา

df = data.drop(['name','cabin','boat','body','home.dest','ticket'], axis=1)#View data set to check dropped column
print(df.head())
print(df.shape)

กำจัด NaN ออกจากตัวข้อมูล

#Remove Missing Value 
df = df.dropna()
#Check Missin Value after drop
df.isnull().sum()

Preprocessing

#Prepare dummy variable for column 'sex' and 'embarked'
#Sex Column
Sex = pd.get_dummies(df['sex'], drop_first=True)
#Embarked Column
Embarked = pd.get_dummies(df['embarked'], drop_first=True)
#PClass Column
PClass = pd.get_dummies(df['pclass'],drop_first=True)
#Concaenate all data set to new data set
titanic_data = pd.concat([df,Sex,Embarked,PClass], axis=1)
#Drop old sex and embarked column
titanic_data = titanic_data.drop(['sex','embarked','pclass'], axis=1)
print(titanic_data.head())

Modeling

ก่อนนำข้อมูลที่เราทำการจัดรูปแบบเข้าสู่ model ต้อง ทำ Standard Scaler ตัวข้อมูลด้วย

#Define features and target variable
X = titanic_data.drop('survived', axis=1) #Feature variables
y = np.ravel(titanic_data.survived)
#Split Data to training set and test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.3, random_state = 1)
#Standardize The data
from sklearn.preprocessing import StandardScaler
# Define the scaler
scaler = StandardScaler()
# Scale the train set
X_train = scaler.fit_transform(X_train)
# Scale the test set
X_test = scaler.fit_transform(X_test)

ตัว Library ที่เราจะใช้กับ Deep Learning คือ keras library ในส่วนของ Initial Constructor เราจะ import ตัว Sequential มาใช้งาน สำหรับตัว Layer แต่ละ Layer ที่เราจะทะยอยใส่ลงไปใน Sequential นั้นเราจะ import Dense โดยเรากำหนดให้ input layer กับ hidden layer ใช้ Relu เป็น activation function และ ตัว output layer เป็น sigmoid function เนื่องจากเราต้องการ output ที่เป็น Binary Classification

# Import `Sequential` from `keras.models`
from keras.models import Sequential
# Import `Dense` from `keras.layers`
from keras.layers import Dense
# Initialize the constructor
model = Sequential()
# Add an input layer
model.add(Dense(12, activation='relu', input_shape=(9,)))
# Add one hidden layer
model.add(Dense(8, activation='relu'))
# Add an output layer
model.add(Dense(1, activation='sigmoid'))

หลังจากเราสร้างตัว algorithm เสร็จก็มาทำการ compile และ fit ตัว model ของเรากับ training set โดยเรากำหนดให้มี epochs = 150 คือให้มีรอบในการทำ iterations ทั้งหมด 150 รอบ ในการทำ back propagation

#Complie and Fit Model
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy'])

model.fit(X_train, y_train,epochs=150, batch_size=10, verbose=1)
#Predict Target Variable from Test Set
y_pred = model.predict_classes(X_test)

เมื่อ predict ค่า y เสร็จแล้ว ลองมาเช็ค Accuracy Score ดูว่า Model ของเราได้ Score เท่าไร

score = model.evaluate(X_test, y_test, verbose=1)
print(score)

ผลออกมาอยู่ที่ 0.8083 หรือ 80.83% ในส่วนของ Accuracy ลองเช็ค Performance Metrics ในมุมอื่นดูบ้างจะให้ภาพรวมออกมาเป็นอย่างไร

#Model Evaluation using Confusion Matrix
cnf_matrix = metrics.confusion_matrix(y_test,y_pred)
print(cnf_matrix)
#Model Accuracy: How often is the classifier correct?
print("Accuracy Score:", round(metrics.accuracy_score(y_test, y_pred)*100,2),"%")
#Model Precision
print("Precision:", round(metrics.precision_score(y_test, y_pred)*100,2), "%")
#Model Recall
print("Recall:", round(metrics.recall_score(y_test, y_pred)*100,2), "%")
#Model F1-Score
print("F1-Score:", round(metrics.f1_score(y_test, y_pred)*100,2), "%")

Conclusion Titanic Data Set Part#4.2

พอดูภาพรวมแล้วตัว Deep Learning ค่อนข้างทำได้ดีกว่า Random Forest เลยทีเดียว Performance Metrics ที่เราเลือกมาวัดค่าทำได้ดี 3 ใน 4 จะมีแค่ค่า Recall ที่ต่ำกว่า Random Forest เล็กน้อย ดูจาก Confusion Matrix สามารถทำนายว่ามีผู้รอดชีวิตจาก Test Setได้ถูกต้อง 93 คน และทำนายผู้เสียชีวิตผิดทั้งที่เป็นผู้รอดชีวิต 43 คน ในส่วนของผู้เสียชีวิตทำนายได้ถูก 160 คน และทำนายได้ผิดทั้งๆที่เป็นเสียชีวิตแต่ model ให้เป็นผู้รอดชีวิต 17 คน

จากที่เรานำเสนอไปข้างต้นตัว Deep Learning ก็ยังสามารถที่จะปรับแต่งเพื่อ optimize ค่าได้อีกโดยเราสามารถทดลองได้จากการเพิ่มจำนวน Layer , ปรับจำนวน node ในแต่ละ Layer เพื่อให้ได้ค่า Performance Metrics ที่ดีขึ้น อันนี้ก็ต้องไปลองทดสอบกันเอาเอง

    Panuwat Ulis

    Written by

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade