모델 저장과 배포
학습이 완료된 모델을 저장하고, 나중에 로드하여 새로운 데이터에 대한 예측을 수행하는 방법을 학습합니다.학습 목표
- joblib과 pickle을 사용하여 모델을 직렬화할 수 있습니다.
- ONNX 형식으로 모델을 변환하여 범용 추론에 활용할 수 있습니다.
- 모델 버전 관리의 기본 원칙을 이해합니다.
모델 저장 실습
import joblib
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
# 파이프라인 포함 모델 학습
pipe = Pipeline([
("scaler", StandardScaler()),
("model", RandomForestClassifier(n_estimators=100, random_state=42))
])
pipe.fit(X_train, y_train)
# 모델 저장 (파이프라인 전체 저장)
joblib.dump(pipe, "model/classifier_pipeline_v1.joblib")
# 모델 로드 및 예측
loaded_pipe = joblib.load("model/classifier_pipeline_v1.joblib")
predictions = loaded_pipe.predict(X_test)
print(f"로드된 모델 정확도: {loaded_pipe.score(X_test, y_test):.4f}")
from skl2onnx import convert_sklearn
from skl2onnx.common.data_types import FloatTensorType
# scikit-learn 모델을 ONNX로 변환
initial_type = [("float_input", FloatTensorType([None, X_train.shape[1]]))]
onnx_model = convert_sklearn(pipe, initial_types=initial_type)
# ONNX 파일 저장
with open("model/classifier_v1.onnx", "wb") as f:
f.write(onnx_model.SerializeToString())
# ONNX Runtime으로 추론
import onnxruntime as rt
import numpy as np
sess = rt.InferenceSession("model/classifier_v1.onnx")
input_name = sess.get_inputs()[0].name
pred = sess.run(None, {input_name: X_test.astype(np.float32)})[0]
print(f"ONNX 추론 결과: {pred[:5]}")
import json
from datetime import datetime
# 모델 메타데이터 저장
metadata = {
"version": "1.0.0",
"created_at": datetime.now().isoformat(),
"model_type": "RandomForestClassifier",
"n_features": X_train.shape[1],
"training_score": float(pipe.score(X_train, y_train)),
"test_score": float(pipe.score(X_test, y_test)),
"hyperparameters": {
"n_estimators": 100,
"max_depth": None,
}
}
with open("model/metadata_v1.json", "w") as f:
json.dump(metadata, f, indent=2, ensure_ascii=False)
저장 형식 비교
| 형식 | 장점 | 단점 | 적합한 상황 |
|---|---|---|---|
| joblib | 빠름, NumPy 최적화 | Python 전용 | 같은 환경에서 재사용 |
| pickle | 표준 라이브러리 | 보안 위험, 느림 | 간단한 저장 |
| ONNX | 범용, 프레임워크 독립 | 변환 복잡도 | 프로덕션 서빙 |
Q: joblib과 pickle 중 어떤 것을 써야 하나요?
Q: joblib과 pickle 중 어떤 것을 써야 하나요?
scikit-learn 모델은 joblib을 권장합니다. NumPy 배열이 포함된 객체를 더 효율적으로 저장하고, 큰 모델의 경우 압축 옵션도 제공합니다.
Q: ONNX는 언제 사용하나요?
Q: ONNX는 언제 사용하나요?
Python 외 환경(C++, Java, JavaScript)에서 추론해야 하거나, 프레임워크에 독립적인 모델 배포가 필요할 때 ONNX를 사용합니다.
체크리스트
- joblib로 모델을 저장하고 로드할 수 있다
- 파이프라인 전체를 하나의 파일로 저장할 수 있다
- ONNX 변환의 목적을 설명할 수 있다
- 모델 메타데이터를 함께 관리하는 습관을 갖추었다

