Day: January 10, 2019

  • python #05 – การ Save/Load ตัวโมเดลจาก Keras แล้วนำไปใช้ใน Production Server

    ต่อจาก python #03 – Train/Validation/Test and Accuracy Assessment with Confusion Matrix

    เมื่อสร้าง Neural Network Model แล้วทำการ Train/Test ปรับค่า Hyper parameters จนได้ผลเป็นที่พอใจแล้ว (Accuracy และ Confusion Matrix ให้ค่าที่รับได้) ก็สามารถเก็บ Model นี้เอาไว้ใช้งานภายหลัง ไม่ต้องเริ่มต้น Train ใหม่ โดยใช้คำสั่ง

    ก็จะได้ไฟล์ (ตามตัวอย่างนี้) ชื่อ example_model.h5 สามารถนำไปใช้บนเครื่อง Production ได้ โดยเรียกใช้งานด้วยคำสั่ง

    จากนั้น ก็จะสามารถใช้ mode.predict() เพื่อใช้งานได้ตามต้องการ

    ต่อ การสร้าง RESTful API สำหรับใช้งานจริง ง่าย ๆ ด้วย Flask และ Waitress ก็สามารถนำ Model นี้ไป Deploy เป็น RESTful API ได้เช่นกัน โดยเพิ่ม

    # load Model
    from keras.models import load_model
    model = load_model('example_model.h5')

    และ

    y_predict=model.predict(data)		
    result=y_predict.argmax(axis=1)[0]

    จากนั้น ก็สั่ง

    python waitress_server.py

    เพื่อส่งค่าผ่าน Postman ไป ที่ Server ก็จะ Error ว่า

    เหตุ เพราะยังไม่ได้มีการสร้าง Tensorflow Graph ขึ้นมา ดังนั้น ต้องเพิ่มคำสั่งต่อไปนี้

    # Tensorflow Graph
    import numpy as np
    import tensorflow as tf
    graph = tf.get_default_graph()

    และ

    with graph.as_default():
         y_predict=model.predict(np_data)

    จากนั้น restart waitress_server แล้วส่งค่าเข้าไปใหม่

    ก็จะได้การ Prediction แล้ว

    หวังว่าจะเป็นประโยชน์ครับ