모델 배포

Python으로 설계하는 Machine Learning 워크플로

Dr. Chris Anagnostopoulos

Honorary Associate Professor

특징 선택, 모델 선택, 튜닝, 학습을 포함한 모델 파이프라인 객체를 운영 파이프라인에 배포하고, 운영에서는 적합된 파이프라인으로 예측을 수행합니다.

Python으로 설계하는 Machine Learning 워크플로

모델 직렬화

분류기를 파일에 저장:

import pickle
clf = RandomForestClassifier().fit(X_train, y_train)
with open('model.pkl', 'wb') as file:
    pickle.dump(clf, file=file)

파일에서 다시 로드:

with open('model.pkl', 'rb') as file:
    clf2 = pickle.load(file)
Python으로 설계하는 Machine Learning 워크플로

파이프라인 직렬화

개발 환경:

vt = SelectKBest(f_classif).fit(
    X_train, y_train)
clf = RandomForestClassifier().fit(
    vt.transform(X_train), y_train)
with open('vt.pkl', 'wb') as file: 
     pickle.dump(vt)
with open('clf.pkl', 'wb') as file: 
     pickle.dump(clf)

특징 선택기 객체와 학습된 모델을 각각 별도로 운영에 배포해야 하는 워크플로.

Python으로 설계하는 Machine Learning 워크플로

파이프라인 직렬화

운영 환경:

with open('vt.pkl', 'rb') as file: 
    vt = pickle.load(vt)
with open('clf.pkl', 'rb') as file: 
    clf = pickle.load(clf)
clf.predict(vt.transform(X_new))

특징 선택기 객체와 학습된 모델을 각각 별도로 운영에 배포해야 하는 워크플로.

Python으로 설계하는 Machine Learning 워크플로

파이프라인 직렬화

개발 환경:

pipe = Pipeline([
    ('fs', SelectKBest(f_classif)), 
    ('clf', RandomForestClassifier())
])
params = dict(fs__k=[2, 3, 4],
    clf__max_depth=[5, 10, 20])
gs = GridSearchCV(pipe, params)
gs = gs.fit(X_train, y_train)

with open('pipe.pkl', 'wb') as file: pickle.dump(gs, file)

특징 선택과 모델 학습을 하나의 파이프라인 객체에 담은 최적화된 워크플로.

Python으로 설계하는 Machine Learning 워크플로

파이프라인 직렬화

운영 환경:

with open('pipe.pkl', 'rb') as file:
   gs = pickle.dump(gs, file)
gs.predict(X_test)

특징 선택과 모델 학습을 하나의 파이프라인 객체에 담은 최적화된 워크플로.

Python으로 설계하는 Machine Learning 워크플로

사용자 정의 특징 변환

   checking_status  duration       ...        own_telephone  foreign_worker
0                1         6       ...                    1               1
1                0        48       ...                    0               1
def negate_second_column(X):
    Z = X.copy()
    Z[:,1] = -Z[:,1]
    return Z
pipe = Pipeline([('ft', FunctionTransformer(negate_second_column)), 
    ('clf', RandomForestClassifier())])
Python으로 설계하는 Machine Learning 워크플로

운영 준비 완료!

Python으로 설계하는 Machine Learning 워크플로

Preparing Video For Download...