1. 모델 서빙
모델이 만들어 지는 과정
모델을 트레이닝 시킨다 => 모델의 트레이닝 시킨 모델을 저장한다 => 모델을 새로온 데이터에 적용시켜본다
이제 끝인 서빙이다
1. 기본구조
import itertools
from utils import clean_text
class ModelHandler:
def __init__(self):
self.id2label = {0: 'negative', 1: 'positive'}
def _clean_text(self, text):
model_input = []
if isinstance(text, str):
cleaned_text = clean_text(text)
model_input.append(cleaned_text)
elif isinstance(text, (list, tuple)) and len(text) > 0 and (all(isinstance(t, str) for t in text)):
cleaned_text = itertools.chain((clean_text(t) for t in text))
model_input.extend(cleaned_text)
else:
model_input.append('')
return model_input
class ModelHandler(BaseHandler):
def __init__(self):
#기본적 데이터
pass
def initialize(self, **kwargs):
# 여긴 초기화
# configuration 등 초기화
# optional 신경망을 구성하고 초기화
# 사전 학습한 모델이나 전처리기 불러오기 (de-serializtion)
# tip 모델은 전역변수로 불러와야 합니다. 만약 inference를 할때마다 불러오면 느려진다
pass
def preprocess(self, data):
# 입력된값을 전처리함
# raw input 전처리 데이터 클린징 목적과 학습된 모델의 학습 당시 scaling이나 처리방식과 맞춰 주는 것이 피료요
# 모델에 입력가능한 형태로 변환 vectorization, converting to id 등의 작업
# 간단히 돌아가게 타입 변경
pass
def inference(self, data):
# 불러온 모델 추론
# 각 모델의 predict 방시으로 예측 확률 분포 값 반환
pass
def postprocess(self, data):
# 모델의 추론 결과를 보정과 조정을 한다
# 에측된 결과에 대한 후처리
# 보통모델이 반환하는 건 확률분포와 같은 값이기 때문에 response에서 받아야 하는 정보로 처리하는 역할을 많이함
pass
def handle(self, data):
# 요청을 받아 적절히 응답
# 정의된 양식으로 데이터가 입력됬는지확인 initialize()
# 입력값에 대한 전처리 및 모델에 입력하기위한 형태로 변환 preprocess()
# 모델 추론 inference()
# 모델 반환값의 후처리 작업 postprocess()
# 결과 반환
pass
여러가지 자료구조에 대하여 써져 있었다
2. 처리후
import itertools
from utils import clean_text
class ModelHandler:
def __init__(self):
self.id2label = {0: 'negative', 1: 'positive'}
def _clean_text(self, text):
model_input = []
if isinstance(text, str):
cleaned_text = clean_text(text)
model_input.append(cleaned_text)
elif isinstance(text, (list, tuple)) and len(text) > 0 and (all(isinstance(t, str) for t in text)):
cleaned_text = itertools.chain((clean_text(t) for t in text))
model_input.extend(cleaned_text)
else:
model_input.append('')
return model_input
class MLModelHandler(ModelHandler):
def __init__(self):
super().__init__()
self.initialize()
def initialize(self, ):
import joblib
self.model = joblib.load('model/ml_model.pkl')
self.vectorizer = joblib.load('model/ml_vectorizer.pkl')
def preprocess(self, data):
model_input = self._clean_text(data)
model_input = self.vectorizer.transform(model_input)
return model_input
def inference(self, model_input):
# get predictions from model as probabilities
model_output = self.model.predict_proba(model_input)
return model_output
def postprocess(self, model_output):
# process predictions to predicted label and output format
predicted_probabilities = model_output.max(axis=1)
predicted_ids = model_output.argmax(axis=1)
predicted_lables = [self.id2label[id_] for id_ in predicted_ids]
return predicted_lables, predicted_probabilities
def handle(self, data):
# 코드는 topknell.tistory.com/47
model_input = self.preprocess(data)
model_output = self.inference(model_input)
return self.postprocess(model_output)
알고리즘에 따른 실행 속도에 대하여 보여줬다
www.youtube.com/embed/UwjOQE9jLBA"
2. 모델 실행해 보기
#터미널
python
from model import MLModelHandler
ml_handler = MLModelHandler()
text = ['정말 재미있는 영화입니다.', '정말 재미가 없습니다.']
result = ml_handler.handle(text)
print(result)
해보면된다
3. 영상 찍은거
'Programmers > 데브코스 인공지능' 카테고리의 다른 글
[프로그래머스 스쿨 AI] Weak 4 EDA (0) | 2021.05.13 |
---|---|
[프로그래머스 스쿨 AI] Weak 4 딥러닝 모델 서빙 및 flask 로 보내기 (0) | 2021.05.12 |
[프로그래머스 스쿨 AI] Weak 4 aws 모델 만들기 (0) | 2021.05.12 |
[프로그래머스 스쿨 AI] Weak 4 클라우드 서버 (0) | 2021.05.11 |
[프로그래머스 스쿨 AI] Weak 4 Flask (0) | 2021.05.11 |