การวิเคราะห์ประสิทธิภาพ Machine Learning Model ด้วย Learning Curve

Chawala Pancharoen
10 min readSep 30, 2020
source

Learning Curve เป็นสิ่งที่แสดงถึงประสิทธิภาพการเรียนรู้ของ Model จาก Training Dataset โดยประสิทธิภาพของ Model จะถูกวัดหลังจากการปรับค่า Weight และค่า Bias ด้วยข้อมูล 2 ชนิด ได้แก่

  1. Training Dataset ที่ Model กำลังเรียนรู้
  2. Validation Dataset ที่ไม่เคยถูกใช้สอน Model มาก่อน

ประสิทธิภาพของ Model จะวัดจาก

  • Loss ยิ่งค่า Loss ของ Model น้อย แสดงว่า Model มีการเรียนรู้ที่ดี
  • Accuracy ยิ่งค่า Accuracy ค่า Accuracy มากแสดงว่า Model มีการเรียนรู้ที่ดี

การวินิจฉัยและแก้ไขปัญหาการเรียนรู้ของ Model เช่น ปัญหา Underfitting และ ปัญหา Overfitting จะต้องมีความเข้าใจรูปแบบ Learning Curve ที่เกิดขึ้น นอกจากนี้สามารถพิจารณาจาก Learning Curve ได้ว่า Training Dataset และ Validation Dataset เป็นตัวแทนของ Data ที่เหมาะสมในกระบวนการพัฒนา Model หรือไม่

รูปแบบของ Learning Curve ที่สำคัญได้แก่

Underfit Learning Curve คือ Model ไม่สามารถเรียนรู้ได้จาก Training Dataset

Overfit Learning Curve คือ Model มีการเรียนรู้ที่ดีเกินไปจาก Training Dataset รวมทั้งรูปแบบของ Noise หรือความผันผวนของ Training Dataset

Good Fit Learning Curve คือ Model มีการเรียนรู้ที่ดี เราสามารถนำ Model ไป Predict ข้อมูลที่ไม่เคยพบเห็นได้อย่างแม่นยำ หรือเรียกว่า Model มีความเป็น Generalize ต่อ Data ใหม่ๆ (มี Generalization Error น้อย)

—รูปแบบของ Learning Curve ที่แสดงว่า Training Dataset และ Validation Dataset เป็นตัวแทนของ Data ที่ไม่ดี คือ Unrepresentative Train Dataset และ Unrepresentative Validation Dataset

workshop

ในที่นี้จะใช้ 2 datasetในการทำแต่ละรูปแบบของ Learning Curve

— First Dataset —

reuters จาก Tensorflow คือ บริการส่งข้อมูลทางอิเล็กทรอนิกส์ที่ให้ข่าวสารล่าสุดข้อมูลอัปเดตเกี่ยวกับตลาดการเงินและข้อมูลอื่น ๆ

Underfit Learning Curve

โดยจะจำลองสถานการณ์ของ Model ที่มีปัญหาการเรียนรู้แบบ Underfit ด้วยการพัฒนา Model เพื่อทำ Sentiment Analysis จาก reuters ดังต่อไปนี้

  1. Import Library ที่จำเป็นต้องใช้
from tensorflow.keras.datasets import reuters
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import SGD
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.preprocessing import sequence
import plotly
import plotly.graph_objs as go
import plotly.express as px
from matplotlib import pyplotimport numpyfrom sklearn.datasets import make_moons, make_circles, make_blobs
from pandas import DataFrame
from sklearn.model_selection import train_test_splitimport pandas as pd

2. Load Dataset

top_words = 5000
(X_train, y_train), (X_test, y_test) = reuters.load_data(num_words=top_words)
max_words = 500
X_train.shape

3. Concat Train และ Test Dataset เพื่อคำนวณคำที่ไม่ซ้ำทั้งหมด

X = numpy.concatenate((X_train, X_test), axis=0)
y = numpy.concatenate((y_train, y_test), axis=0)
print("Number of words: ")
print(len(numpy.unique(numpy.hstack(X))))

4. ดูความยาวของคำในประโยค

print("Review length: ")
result = [len(x) for x in X]
print("Mean %.2f words (%f)" % (numpy.mean(result), numpy.std(result)))
pyplot.boxplot(result)
pyplot.show()

5. เติม 0 (ศูนย์) เพื่อทำให้ความยาวของประโยคเท่ากัน (Padding)

X_train = sequence.pad_sequences(X_train, maxlen=max_words)
X_test = sequence.pad_sequences(X_test, maxlen=max_words)
X_train.shape

6. นิยาม Model

model = Sequential()
model.add(Dense(8, input_dim=max_words, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
model.summary()

7. Train Model

history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=100, batch_size=120, verbose=2)

8. Plot Loss

plotly.offline.init_notebook_mode(connected=True)h1 = go.Scatter(y=history.history['loss'], 
mode="lines", line=dict(
width=2,
color='blue'),
name="loss"
)
h2 = go.Scatter(y=history.history['val_loss'],
mode="lines", line=dict(
width=2,
color='red'),
name="val_loss"
)
data = [h1,h2]
layout1 = go.Layout(title='Loss',
xaxis=dict(title='epochs'),
yaxis=dict(title=''))
fig1 = go.Figure(data = data, layout=layout1)
plotly.offline.iplot(fig1, filename="Intent Classification")

9. Plot Accuracy

h1 = go.Scatter(y=history.history['accuracy'], 
mode="lines", line=dict(
width=2,
color='blue'),
name="acc"
)
h2 = go.Scatter(y=history.history['val_accuracy'],
mode="lines", line=dict(
width=2,
color='red'),
name="val_acc"
)
data = [h1,h2]
layout1 = go.Layout(title='Accuracy',
xaxis=dict(title='epochs'),
yaxis=dict(title=''))
fig1 = go.Figure(data = data, layout=layout1)
plotly.offline.iplot(fig1, filename="Intent Classification")

Overfit Learning Curve

โดยจะจำลองสถานการณ์ของ Model ที่มีปัญหาการเรียนรู้แบบ Overfitting ด้วยการพัฒนา Model เพื่อ Classfify ข้อมูลจำนวน 2 Class ดังต่อไปนี้

  1. สร้าง Dataset แบบ 2 Class โดยใช้ Function make_circles ของ Sklearn
X, y =  make_circles(n_samples=500, noise=0.2, random_state=1)

2. แบ่งข้อมูลสำหรับ Train และ Test โดยการสุ่มในสัดส่วน 50:50

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, shuffle= True)X_train.shape, X_test.shape, y_train.shape, y_test.shape

3. นำ Dataset ส่วนที่ Train มาแปลงเป็น DataFrame โดยเปลี่ยนชนิดข้อมูลใน Column “class” เป็น String เพื่อทำให้สามารถแสดงสีแบบไม่ต่อเนื่องได้ แล้วนำไป Plot

X_train_pd = pd.DataFrame(X_train, columns=['x', 'y'])
y_train_pd = pd.DataFrame(y_train, columns=['class'])
df = pd.concat([X_train_pd, y_train_pd], axis=1)
fig = px.scatter(df, x="x", y="y", color="class")
fig.show()

4. นิยาม Model

model = Sequential()
model.add(Dense(60, input_dim=2, activation='relu'))
model.add(Dense(30, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

5. Train Model

his = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=500, verbose=1)

6. Plot Loss

plotly.offline.init_notebook_mode(connected=True)h1 = go.Scatter(y=his.history['loss'], 
mode="lines", line=dict(
width=2,
color='blue'),
name="loss"
)
h2 = go.Scatter(y=his.history['val_loss'],
mode="lines", line=dict(
width=2,
color='red'),
name="val_loss"
)
data = [h1,h2]
layout1 = go.Layout(title='Loss',
xaxis=dict(title='epochs'),
yaxis=dict(title=''))
fig1 = go.Figure(data = data, layout=layout1)
plotly.offline.iplot(fig1, filename="Intent Classification")

7. Plot Accuracy

h1 = go.Scatter(y=his.history['accuracy'], 
mode="lines", line=dict(
width=2,
color='blue'),
name="acc"
)
h2 = go.Scatter(y=his.history['val_accuracy'],
mode="lines", line=dict(
width=2,
color='red'),
name="val_acc"
)
data = [h1,h2]
layout1 = go.Layout(title='Accuracy',
xaxis=dict(title='epochs'),
yaxis=dict(title=''))
fig1 = go.Figure(data = data, layout=layout1)
plotly.offline.iplot(fig1, filename="Intent Classification")

ในการวิเคราะห์ปัญหา Overfitting จะพิจารณาจากกราฟ Loss เป็นหลัก ซึ่งจากกราฟ Loss พบว่ายิ่งมีการ Train มากขึ้น ค่า Training Loss จะลงอย่างต่อเนื่อง ขณะที่ Validation Loss จะลดลงถึงจุดหนึ่งแล้วหลังจากนั้นกลับมีการเพิ่มค่าขึ้นเรื่อยๆ

Good Fit Learning Curve

โดยจะจำลองสถานการณ์ของ Model แบบ Good Fitting ด้วยการพัฒนา Model เพื่อ Classify ข้อมูลจำนวน 2 Class ดังต่อไปนี้

  1. สร้าง Dataset แบบ 3 Class โดยใช้ Function make_blobs ของ Sklearn
X, y = make_blobs(n_samples=3000, centers=3, n_features=2, cluster_std=2, random_state=2)

2. แบ่งข้อมูลสำหรับ Train และ Test โดยการสุ่มในสัดส่วน 60:40

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, shuffle= True)X_train.shape, X_test.shape, y_train.shape, y_test.shape

3. นำ Dataset ส่วนที่ Train มาแปลงเป็น DataFrame โดยเปลี่ยนชนิดข้อมูลใน Column “class” เป็น String เพื่อทำให้สามารถแสดงสีแบบไม่ต่อเนื่องได้ แล้วนำไป Plot

X_train_pd = pd.DataFrame(X_train, columns=['x', 'y'])
y_train_pd = pd.DataFrame(y_train, columns=['class'])
df = pd.concat([X_train_pd, y_train_pd], axis=1)
df["class"] = df["class"].astype(str)
fig = px.scatter(df, x="x", y="y", color="class")
fig.show()

4. เข้ารหัสผลเฉลย แบบ One-Hot Encoding เพื่อที่ว่าเมื่อ Model มีการ Predict ว่าเป็น Class ไหน มันจะให้ค่าความมั่นใจ (Confidence) กลับมาด้วย

y_train = to_categorical(y_train)
y_test = to_categorical(y_test)

5. นิยาม Model

model = Sequential()
model.add(Dense(50, input_dim=2, activation='relu', kernel_initializer='he_uniform'))
model.add(Dense(3, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.summary()

6. Train Model

his = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=200, verbose=1)

7. Plot Loss

plotly.offline.init_notebook_mode(connected=True)h1 = go.Scatter(y=his.history['loss'], 
mode="lines", line=dict(
width=2,
color='blue'),
name="loss"
)
h2 = go.Scatter(y=his.history['val_loss'],
mode="lines", line=dict(
width=2,
color='red'),
name="val_loss"
)
data = [h1,h2]
layout1 = go.Layout(title='Loss',
xaxis=dict(title='epochs'),
yaxis=dict(title=''))
fig1 = go.Figure(data = data, layout=layout1)
plotly.offline.iplot(fig1, filename="Intent Classification")

8. Plot Accuracy

h1 = go.Scatter(y=his.history['accuracy'], 
mode="lines", line=dict(
width=2,
color='blue'),
name="acc"
)
h2 = go.Scatter(y=his.history['val_accuracy'],
mode="lines", line=dict(
width=2,
color='red'),
name="val_acc"
)
data = [h1,h2]
layout1 = go.Layout(title='Accuracy',
xaxis=dict(title='epochs'),
yaxis=dict(title=''))
fig1 = go.Figure(data = data, layout=layout1)
plotly.offline.iplot(fig1, filename="Intent Classification")

ในการวิเคราะห์ปัญหา Overfitting จะพิจารณาจากกราฟ Loss เป็นหลัก ซึ่งจากกราฟ Loss ด้านบน พบว่ายิ่งมีการ Train มากขึ้น ค่า Training Loss จะลงอย่างต่อเนื่อง ขณะที่ Validation Loss จะลดลงถึงจุดหนึ่งแล้วหลังจากนั้นกลับมีการเพิ่มค่าขึ้นเรื่อยๆ

Unrepresentative Train Dataset

โดยจะจำลองสถานการณ์เมื่อ Trainning Dataset ไม่สามารถเป็นตัวแทนของข้อมูลที่ดีได้ ดังต่อไปนี้

  1. สร้าง Dataset แบบ 3 Class โดยใช้ Function make_blobs ของ Sklearn
X, y = make_blobs(n_samples=100, centers=3, n_features=2, cluster_std=2, random_state=2)

2. แบ่งข้อมูลสำหรับ Train และ Test โดยการสุ่มในสัดส่วน 50:50

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, shuffle= True)X_train.shape, X_test.shape, y_train.shape, y_test.shape

3. นำ Dataset ส่วนที่ Train มาแปลงเป็น DataFrame โดยเปลี่ยนชนิดข้อมูลใน Column “class” เป็น String เพื่อทำให้สามารถแสดงสีแบบไม่ต่อเนื่องได้ แล้วนำไป Plot

X_train_pd = pd.DataFrame(X_train, columns=['x', 'y'])
y_train_pd = pd.DataFrame(y_train, columns=['class'])
df = pd.concat([X_train_pd, y_train_pd], axis=1)
df["class"] = df["class"].astype(str)
fig = px.scatter(df, x="x", y="y", color="class")
fig.show()

4. เข้ารหัสผลเฉลย แบบ One-Hot Encoding เพื่อที่ว่าเมื่อ Model มีการ Predict ว่าเป็น Class ไหน มันจะให้ค่าความมั่นใจ (Confidence) กลับมาด้วย

y_train = to_categorical(y_train)
y_test = to_categorical(y_test)

5. นิยาม Model

model = Sequential()
model.add(Dense(50, input_dim=2, activation='relu', kernel_initializer='he_uniform'))
model.add(Dense(3, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

6. Train Model

his = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=200, verbose=1)

7. Plot Loss

plotly.offline.init_notebook_mode(connected=True)h1 = go.Scatter(y=his.history['loss'], 
mode="lines", line=dict(
width=2,
color='blue'),
name="loss"
)
h2 = go.Scatter(y=his.history['val_loss'],
mode="lines", line=dict(
width=2,
color='red'),
name="val_loss"
)
data = [h1,h2]
layout1 = go.Layout(title='Loss',
xaxis=dict(title='epochs'),
yaxis=dict(title=''))
fig1 = go.Figure(data = data, layout=layout1)
plotly.offline.iplot(fig1, filename="Intent Classification")

8. Plot Accuracy

h1 = go.Scatter(y=his.history['accuracy'], 
mode="lines", line=dict(
width=2,
color='blue'),
name="acc"
)
h2 = go.Scatter(y=his.history['val_accuracy'],
mode="lines", line=dict(
width=2,
color='red'),
name="val_acc"
)
data = [h1,h2]
layout1 = go.Layout(title='Accuracy',
xaxis=dict(title='epochs'),
yaxis=dict(title=''))
fig1 = go.Figure(data = data, layout=layout1)
plotly.offline.iplot(fig1, filename="Intent Classification")

จากกราฟพบว่าเมื่อมีการ Train Model มากขึ้น ค่า Loss จะมีแนวโน้มลดลง และ Accuracy มีแนวโน้มเพิ่มขึ้น แต่จะมี Gap ระหว่าง Training Loss กับ Validation Loss รวมทั้ง Gap ระหว่าง Training Accuracy กับ Validation Accuracy สูง ซึ่งแสดงว่ามี Training Dataset น้อยไป ไม่เพียงพอในการ Train Model

Unrepresentative Validation Dataset มี 2 สถานการณ์ดังนี้

  • สถานการณ์ที่ 1 — Validation Dataset น้อย และไม่สามารถเป็นตัวแทนของ Validation Dataset ได้
  1. สร้าง Dataset แบบ 3 Class โดยใช้ Function make_blobs ของ Sklearn
X, y = make_blobs(n_samples=500, centers=3, n_features=2, cluster_std=10, random_state=2)

2. แบ่งข้อมูลสำหรับ Train และ Test โดยการสุ่มในสัดส่วน 95:5

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.05, shuffle= True)X_train.shape, X_test.shape, y_train.shape, y_test.shape

3. นำ Dataset ส่วนที่ Train มาแปลงเป็น DataFrame โดยเปลี่ยนชนิดข้อมูลใน Column “class” เป็น String เพื่อทำให้สามารถแสดงสีแบบไม่ต่อเนื่องได้ แล้วนำไป Plot

X_train_pd = pd.DataFrame(X_train, columns=['x', 'y'])
y_train_pd = pd.DataFrame(y_train, columns=['class'])
df = pd.concat([X_train_pd, y_train_pd], axis=1)
df["class"] = df["class"].astype(str)
fig = px.scatter(df, x="x", y="y", color="class")
fig.show()

4. เข้ารหัสผลเฉลย แบบ One-Hot Encoding เพื่อที่ว่าเมื่อ Model มีการ Predict ว่าเป็น Class ไหน มันจะให้ค่าความมั่นใจ (Confidence) กลับมาด้วย

y_train = to_categorical(y_train)
y_test = to_categorical(y_test)

5. นิยาม Model

model = Sequential()
model.add(Dense(50, input_dim=2, activation='relu', kernel_initializer='he_uniform'))
model.add(Dense(3, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

6. Train Model

his = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=200, verbose=1)

7. Plot Loss

plotly.offline.init_notebook_mode(connected=True)h1 = go.Scatter(y=his.history['loss'], 
mode="lines", line=dict(
width=2,
color='blue'),
name="loss"
)
h2 = go.Scatter(y=his.history['val_loss'],
mode="lines", line=dict(
width=2,
color='red'),
name="val_loss"
)
data = [h1,h2]
layout1 = go.Layout(title='Loss',
xaxis=dict(title='epochs'),
yaxis=dict(title=''))
fig1 = go.Figure(data = data, layout=layout1)
plotly.offline.iplot(fig1, filename="Intent Classification")

8. Plot Accuracy

h1 = go.Scatter(y=his.history['accuracy'], 
mode="lines", line=dict(
width=2,
color='blue'),
name="acc"
)
h2 = go.Scatter(y=his.history['val_accuracy'],
mode="lines", line=dict(
width=2,
color='red'),
name="val_acc"
)
data = [h1,h2]
layout1 = go.Layout(title='Accuracy',
xaxis=dict(title='epochs'),
yaxis=dict(title=''))
fig1 = go.Figure(data = data, layout=layout1)
plotly.offline.iplot(fig1, filename="Intent Classification")

ในกรณีที่ Validation Dataset น้อย และไม่สามารถเป็นตัวแทนของ Validation Dataset ได้จะเห็นค่า Training Loss ค่อยๆ ลดลงแบบเดียวกับในกรณี Good Fitting แต่ Validation Loss จะแกว่งไปมาเหมือนการสุ่มอยู่รอบๆ กราฟ Training Loss เช่นเดียวกันกับที่เมื่อพิจารณาจากกราฟ Accuracy จะพบว่าค่า Validation Accuracy จะแกว่งไปมาเหมือนการสุ่มอยู่รอบๆ กราฟ Training Accuracy

  • สถานการณ์ที่ 2 — Validation Dataset น้อย และง่ายเกินไป
  1. สร้าง Dataset แบบ 3 Class โดยใช้ Function make_blobs ของ Sklearn
X, y = make_blobs(n_samples=500, centers=3, n_features=2, cluster_std=2, random_state=2)

2. แบ่งข้อมูลสำหรับ Train และ Test โดยการสุ่มในสัดส่วน 97:3

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.03, shuffle= True)X_train.shape, X_test.shape, y_train.shape, y_test.shape

3. นำ Dataset ส่วนที่ Train มาแปลงเป็น DataFrame โดยเปลี่ยนชนิดข้อมูลใน Column “class” เป็น String เพื่อทำให้สามารถแสดงสีแบบไม่ต่อเนื่องได้ แล้วนำไป Plot

X_train_pd = pd.DataFrame(X_train, columns=['x', 'y'])
y_train_pd = pd.DataFrame(y_train, columns=['class'])
df = pd.concat([X_train_pd, y_train_pd], axis=1)
df["class"] = df["class"].astype(str)
fig = px.scatter(df, x="x", y="y", color="class")
fig.show()

4. เข้ารหัสผลเฉลย แบบ One-Hot Encoding เพื่อที่ว่าเมื่อ Model มีการ Predict ว่าเป็น Class ไหน มันจะให้ค่าความมั่นใจ (Confidence) กลับมาด้วย

y_train = to_categorical(y_train)
y_test = to_categorical(y_test)

5. นิยาม Model

model = Sequential()
model.add(Dense(50, input_dim=2, activation='relu', kernel_initializer='he_uniform'))
model.add(Dense(3, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

6. Train Model

his = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=200, verbose=1)

7. Plot Loss

plotly.offline.init_notebook_mode(connected=True)h1 = go.Scatter(y=his.history['loss'], 
mode="lines", line=dict(
width=2,
color='blue'),
name="loss"
)
h2 = go.Scatter(y=his.history['val_loss'],
mode="lines", line=dict(
width=2,
color='red'),
name="val_loss"
)
data = [h1,h2]
layout1 = go.Layout(title='Loss',
xaxis=dict(title='epochs'),
yaxis=dict(title=''))
fig1 = go.Figure(data = data, layout=layout1)
plotly.offline.iplot(fig1, filename="Intent Classification")

8. Plot Accuracy

h1 = go.Scatter(y=his.history['accuracy'], 
mode="lines", line=dict(
width=2,
color='blue'),
name="acc"
)
h2 = go.Scatter(y=his.history['val_accuracy'],
mode="lines", line=dict(
width=2,
color='red'),
name="val_acc"
)
data = [h1,h2]
layout1 = go.Layout(title='Accuracy',
xaxis=dict(title='epochs'),
yaxis=dict(title=''))
fig1 = go.Figure(data = data, layout=layout1)
plotly.offline.iplot(fig1, filename="Intent Classification")

ในกรณีที่ Validation Dataset น้อย และง่ายจนเกินไป จะเห็นค่า Training Loss และ Validate Loss ลดลง โดยที่ค่า Validate Loss จะต่ำกว่า Training Lossในทางตรงกันข้าม เมื่อพิจารณาจากกราฟ Accuracy จะพบว่าค่า Training Accuracy และ Validate Accuracy จะเพิ่มขึ้น โดยที่ค่า Validate Accuracy จะสูงกว่า Training Accuracy

— Second Dataset —

เป็นข้อมูลรูปภาพที่ import จาก Tensorflow

  1. Import Library ที่จำเป็นต้องใช้
import numpy as np
import matplotlib.pyplot as plt
import plotly
import plotly.graph_objs as go
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D ,MaxPool2D
import pickle as p
import tensorflow as tf
to_categorical = tf.keras.utils.to_categorical

2. Load Dataset

from tensorflow.keras.datasets import cifar10
(in_train, out_train), (in_test, out_test) = cifar10.load_data()

3. นำภาพที่มีค่าของ Pixel เป็นจำนวนเต็มระหว่าง 0–255 เข้า Model ได้โดยตรง แต่ก็อาจทำให้ Train Model ได้ช้า รวมทั้งอาจส่งผลต่อประสิทธิภาพในการทำนาย ดังนั้นเราจึงต้องมีการทำ Scaling เพื่อปรับค่าของ Pixel เป็นตัวเลขทศนิยม ซึ่งเราจะใช้เทคนิคพื้นฐานในการทำ Scaling ให้มีค่าระหว่าง 0–1 โดยการหารด้วย 255

in_train = in_train/255
in_test = in_test/255

4. แบ่งข้อมูลสำหรับ Train และ Test

out_cat_train = to_categorical(out_train, 10)
out_cat_test = to_categorical(out_test, 10)

5.นิยาม model

model = Sequential()
model.add(Conv2D(filters=32, kernel_size=(4,4), input_shape=(32,32,3), activation='relu',))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Conv2D(filters=32, kernel_size=(4,4), input_shape=(32,32,3), activation='relu',))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Flatten())
model.add(Dense(256, activation='relu'))
model.add(Dense(10, activation='softmax'))
model.summary(

6. Compile Model

model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

7. Train Model

model.fit(in_train, out_cat_train, epochs=15, validation_data=(in_test, out_cat_test))

8. นำ Dataset ส่วนที่ Train มาแปลงเป็น DataFrame

metrics = pd.DataFrame(model.history.history)
metrics

9. Plot Loss

metrics[['loss', 'val_loss']].plot()

10. Plot Accuracy

metrics[['accuracy', 'val_accuracy']].plot()

จากกราฟด้านบนพบว่าเมื่อมีการ Train Model มากขึ้น ค่า Loss จะมีแนวโน้มลดลง และ Accuracy มีแนวโน้มเพิ่มขึ้น แต่จะมี Gap ระหว่าง Training Loss กับ Validation Loss รวมทั้ง Gap ระหว่าง Training Accuracy กับ Validation Accuracy สูง ซึ่งแสดงว่าเรามี Training Dataset น้อยไป ไม่เพียงพอในการ Train Model เป็นปัญหาแบบ Unrepresentative Train Dataset

Reference

--

--