Image Classification
วันนี้เราจะมาทำ Image Classification กันนะครับโดยจะทำการแยกผลไม้ชนิดต่างๆ
Image Classification คืออะไร ?
Image Classification คือ กระบวนการการแยกรูปออกเป็นส่วนๆ เราจะสามารถแยกรูปต่างๆได้ว่าในรูปนั้นมันคืออะไรโดยการใช้ CNN
CNN (Convolutional Neural Network) เป็นโครงข่ายประสาท มักถูกนำมาใช้ในงาน Computer Vision หรือ วิเคราะห์รูปภาพ
Requirement
เราจะใช้ Google Colaboratory ในการทำกันนะครับหรือใครจะทำใน Jupyter Notebookก็ได้ครับทำคล้ายๆกัน
มาเตรียม Data Set กันเลยครับ
หารูปผลไม้ต่างๆที่เราอยากแยกชนิดมาแยกไว้ตามโฟลเดอร์จะได้สะดวกเวลานำไปใช้
ขั้นแรกก็เปิด Google Colab ขึ้นมาครับ
คลิ๊กเพื่อเปิด
แล้วเราก็ Import สิ่งต่างๆที่จำเป็นเข้ามา
import tensorflow as tf
import PIL
from tensorflow.keras import layers
import matplotlib.pyplot as plt
import numpy as np
import pickle as p
import plotly
from tensorflow.keras.models import load_model
from tensorflow.keras.models import model_from_json
import plotly.graph_objs as go
from tensorflow import keras
from tensorflow.keras.models import Sequential
นำ Data Set ที่เราเตรียมไว้มาใช้
import pathlib
path = “/content/drive/My Drive/Fruit” #”/content/drive/My Drive/โฟลเดอร์ที่สร้างไว้”
data_dir = pathlib.Path(path)
เสร็จแล้วก็มาลองนับรูปนdata setกันว่าครบที่เราเตรียมไว้ไหม
จัดการรูปแบบขนาดของ data set
batch_size คือ ค่าที่กำหนดขนาดของการอ่านข้อมูล
img_height คือ ความสูงของรูปภาพ
img_width คือ ความกว้างของรูปภาพ
ทีนี้เราก็มา Trainข้อมูลกัน
train = tf.keras.preprocessing.image_dataset_from_directory(
data_dir,
validation_split=0.2,
subset=”validation”,
seed=123,
image_size=(img_height, img_width),
batch_size=batch_size)
เรามา Validationกันต่อเลย
val_ds = tf.keras.preprocessing.image_dataset_from_directory(
data_dir,
validation_split=0.2,
subset=”validation”,
seed=123,
image_size=(img_height, img_width),
batch_size=batch_size)
ตรวจสอบว่ามี class อะไรบ้าง
ลองทดสอบให้แสดงรูป
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 10))
for images, labels in train.take(1):
for i in range(9):
ax = plt.subplot(3, 3, i + 1)
plt.imshow(images[i].numpy().astype(“uint8”))
plt.title(class_names[labels[i]])
plt.axis(“off”)
เช็ครูปแบบของ Data set
มาสร้างModelกันครับ
epochs คือจำนวนรอบที่ต้องการให้ Train
num_classes = 4
epochs=50
model = Sequential([
layers.experimental.preprocessing.Rescaling(1./255, input_shape=(img_height, img_width, 3)),
layers.Conv2D(16, 3, padding=’same’, activation=’relu’),
layers.MaxPooling2D(),
layers.Conv2D(32, 3, padding=’same’, activation=’relu’),
layers.MaxPooling2D(),
layers.Conv2D(64, 3, padding=’same’, activation=’relu’),
layers.MaxPooling2D(),
layers.Flatten(),
layers.Dense(128, activation=’relu’),
layers.Dense(num_classes)])
แสดงความแม่นยำ
Train model สอนให้มันจำกันครับ
epochs=50
history = model.fit(train,
validation_data=val_ds,
epochs=epochs)
หลังจาก Train เสร็จก็มา save ไว้ก่อน
เผื่อเวลาที่เราจะเรียกใช้ model นี้ใหม่เราจะสามารถเรีกมาได้ทันทีโดยไม่ต้องทำการ Train ใหม่
with open(‘history_model’, ‘wb’) as file:
p.dump(his.history, file)
filepath=’model1.h5'
model.save(filepath)
filepath_model = ‘model1.json’
filepath_weights = ‘weights_model.h5’
model_json = model.to_json()
with open(filepath_model, “w”) as json_file:
json_file.write(model_json)
model.save_weights(‘weights_model.h5’)
print(“Saved model to disk”)
ส่วนอันนี้คือไว้ใช้สำหรับเวลาโหลด Model ครับ
with open(‘history_model’, ‘rb’) as file:
his = p.load(file)
filepath=’model1.h5'
filepath_model = ‘model1.json’
filepath_weights = ‘weights_model.h5’
h1 = go.Scatter(y=his[‘loss’],
mode=”lines”, line=dict(
width=2,
color=’blue’),
name=”loss”
)
h2 = go.Scatter(y=his[‘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, layout=layout1)
plotly.offline.iplot(fig1, filename=”testMNIST”)
predict_model = load_model(filepath)
predict_model.summary()
with open(filepath_model, ‘r’) as f:
loaded_model_json = f.read()
predict_model = model_from_json(loaded_model_json)
predict_model.load_weights(filepath_weights)
print(“Loaded model from disk”)
มาถึงขั้นตอนสุดท้าย Prediction
เพื่อทดสอบว่าที่เรา Train ไปเนี่ยมันได้ผลไหมโดยการนำรูปมา1รูปแล้วให้ทายว่าคือรูปอะไร
import requests
from IPython.display import Image
from io import BytesIO
test_path = (“/content/drive/My Drive/testai/test1.jpg”) #เปลี่ยนตรงนี้เป็นที่อยู่ของโฟลเดอร์ที่เรากำหนดไว้
img = keras.preprocessing.image.load_img(test_path, target_size=(img_height, img_width))
img_array = keras.preprocessing.image.img_to_array(img)
img_array = tf.expand_dims(img_array, 0) # Create a batch
predictions = predict_model.predict(img_array)
score = tf.nn.softmax(predictions[0])
print(“apple = “,score[0],”\nbanana = “,score[1],”\ngrape = “,score[2],”\norange = “,score[3])
display(Image(filename=test_path,width=200, height=200))
print(“This is {} {:.4f}%”.format((class_names[np.argmax(score)]), 100 * np.max(score)))
มาดูผลลัพธ์กันครับ
จบแล้วค้าบบการ Train ของเราไว้เจอกันใหม่นะครับสวัสดีครับ