1. 플라스크 설치
$ conda create -n flask-tutorial python=3.0
$ conda activate flask-tutorial
$ pip install Flask
2. Hello World with Flask
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello_world():
return "<p>Hello World</p>"
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=8090)
3. 모델 학습 저장
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
data = load_iris()
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)
model = RandomForestClassifier(n_estimators=300, random_state=RANDOM_SEED)
model.fit(X_train, y_train)
print(f"Accuracy : {accuracy_score(y_test, model.predict(X_test))}")
print(classification_report(y_test, model.predict(X_test)))
os.makedirs("./build", exist_ok=True)
pickle.dump(model, open('./build/model.pkl', 'wb'))
- build 디렉토리 안에 model.pkl이 생성된 것을 확인
$ cd build
$ ls -a
4. 모델 파일을 load하여 flask 서버에 연결
POST /predict API
import pickle
import numpy as np
from flask import Flask, jsonify, request
model = pickle.load(open('./build/model.pkl', 'rb'))
app = Flask(__name__)
@app.route('/predict', methods=['POST'])
def make_predict():
request_body = request.get_json(force=True)
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)
y_test = model.predict(X_test)
response_body = jsonify(result=y_test.tolist())
return response_body
if __name__ == '__main__':
app.run(port=8090, debug=True)
5. API 테스트
$ python app.py
- 서버가 열리면 POST /predict API를 요청하여 결과 반환 값 확인
$ curl -X POST "Content-Type:application/json" --data '{"sepal_length": 5.9, "sepal_width": 3.0, "petal_length": 5.1, "petal_width": 1.8}' http://localhost:8090/predict
- 0, 1, 2 중의 하나의 type으로 classification 하게 된다.