간단한 모델을 만들고 직접 서빙을 해보자!
requirements
소스 코드
import os
import pickle
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, classification_report
from sklearn.model_selection import train_test_split
RANDOM_SEED = 1234
# 1. data load
data = load_iris()
# 2. data split
X = data['data']
y = data['target']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=RANDOM_SEED)
# 3. train model
model = RandomForestClassifier(n_estimator=300, random_state=RANDOM_SEED)
model.fit(X_train, y_train)
# 4. evaluate model
print(f"Accuracy : {accuracy_score(y_test, model.predict(X_test))}")
print(classification_report(y_test, model.predict(X_test)))
# 5. save model to ./build/model.pkl
os.makedirs("./build", exist_ok=True)
pickle.dump(model, open('./build/model.pkl', 'wb'))
python train.py
로 실행build
폴더가 생기고, 안에 model.pkl
파일이 생긴것을 확인할 수 있다.import pickle
import numpy as np
from flask import Flask, jsonify, request
# 지난 시간에 학습한 모델 파일을 불러오기
model = pickle.load(open('./build/model.pkl', 'rb'))
# Flask Server
app = Flask(__name__)
# POST /predict 라는 API 를 구현.
@app.route('/predict', methods=['POST'])
def make_predict():
# API Request Body 를 python dictionary object 로 변환하기.
request_body = request.get_json(force=True)
# request body 를 model 의 형식에 맞게 변환
X_test = [request_body['sepal_length'], request_body['sepal_width'],
request_body['petal_length'], request_body['petal_width']]
X_test = np.array(X_test)
X_test = X_test.reshape(1, -1)
# model 의 predict 함수를 호출하여, prediction 값 구하기
y_test = model.predict(X_test)
# prediction 값을 json화
response_body = jsonify(result=y_test.tolist())
# predict 결과를 담아 API Response Body 를 return
return response_body
if __name__ == '__main__':
app.run(port=5000, debug=True)
위의 Flask server를 run하고
python flask_server.py
해당 Flask server에 POST /predict
API를 요청하여, 어떤 결과가 반환되는지 확인하자.
curl -X POST -H "Content-Type:application/json" --data '{"sepal_length":5.9, "sepal_width": 3.0, "petal_lentgh": 5.1, "petal_width": 1.8}' http:localhost:5000/predict
# {"result":[2]}