데이터 사이언스 · DS09

모델 운영: 매주 돌아가게

5월 1일에 학습한 이탈 모델을 다섯 달 뒤에 그대로 썼더니 순위 실력(AUC 0.688)은 거의 그대로인데, 평균 예측 이탈률은 47.3%로 실제 41.9%보다 5%p 넘게 높아져 있었습니다. 이 장에서는 모델을 파일로 저장하고, 매주 점수 테이블을 만드는 배치 스코어링을 돌리고, 실험을 MLflow에 기록하고, 드리프트를 PSI로 감시합니다. 공고 27건 중 10건(37%)이 MLOps나 배포를 적고, 대부분 우대사항입니다.


학습과 서빙을 나눈다

노트북에서 학습하고 바로 예측하는 것과, 매주 월요일 새벽에 사람 없이 점수가 만들어지는 것은 다른 일입니다. 운영에서는 두 작업을 나눕니다.

학습 작업스코어링(서빙) 작업
언제가끔(월 1회, 또는 성능이 떨어졌을 때)자주(매주, 매일)
입력라벨이 확정된 과거 기준일의 피처 테이블오늘 기준일의 피처 테이블(라벨 없음)
출력모델 파일 + 설명서(버전, 학습 기간, 피처 목록, 성능)점수 테이블(날짜, 유저, 점수, 모델 버전)
실패하면기존 모델을 계속 쓴다어제 점수를 쓰거나 캠페인을 멈춘다. 알림이 필요하다

이탈 모델처럼 주 단위 캠페인에 쓰는 점수는 요청이 올 때마다 계산하는 실시간 서빙이 필요 없습니다. 미리 계산해 테이블에 넣어 두는 배치 스코어링이면 충분하고, 고장 날 곳이 훨씬 적습니다. 그리고 이 구조는 DE 트랙에서 만든 것과 같습니다. 피처 테이블은 dbt 모델로(07장), 주간 실행은 Airflow DAG로(A02, A03), 입력 검사는 dbt 테스트로(08장) 옮기면 됩니다. 09장 캡스톤의 DAG 끝에 "피처 만들기 → 점수 매기기 → 점수 테이블 검사" 세 단계를 붙이는 모양입니다.

Step 1. 스크립트와 결과

"""DS09. 모델 운영: 저장, 배치 스코어링, 실험 기록, 드리프트 감시.  python ds/ds09_ops.py"""
import sys, os, json, datetime
sys.path.insert(0, 'ds')
import _quiet
import duckdb, joblib, numpy as np, pandas as pd, sklearn
from sklearn.metrics import roc_auc_score, brier_score_loss
from features import build, model, NUM, CAT

con = duckdb.connect('data/shop.duckdb', read_only=True)
os.makedirs('out/models', exist_ok=True)

print('## 1. 학습과 저장 (학습 작업)')
TRAIN_CUT = '2026-05-01'
tr = build(con, TRAIN_CUT)
m = model().fit(tr[NUM + CAT], tr.churn)
ver = f'churn_logit_{TRAIN_CUT}'
joblib.dump(m, f'out/models/{ver}.joblib')
meta = {'version': ver, 'train_cutoff': TRAIN_CUT, 'label': '기준일 이후 30일 무접속', 'rows': len(tr), 'churn_rate': round(float(tr.churn.mean()), 4),
        'features': NUM + CAT, 'sklearn': sklearn.__version__, 'trained_at': '2026-11-25',
        'train_auc': round(float(roc_auc_score(tr.churn, m.predict_proba(tr[NUM + CAT])[:, 1])), 4)}
json.dump(meta, open(f'out/models/{ver}.json', 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
print(f'저장: out/models/{ver}.joblib ({os.path.getsize(f"out/models/{ver}.joblib") / 1024:.0f} KB) + 같은 이름의 .json(설명서)')
print(json.dumps({k: meta[k] for k in ['version', 'train_cutoff', 'rows', 'churn_rate', 'sklearn', 'train_auc']}, ensure_ascii=False))

print('\n## 2. 배치 스코어링 (매주 월요일 도는 작업을 5주치 흉내)')
m2 = joblib.load(f'out/models/{ver}.joblib')                       # 서빙 작업은 학습 코드를 모른다. 파일과 피처 목록만 안다
feats = json.load(open(f'out/models/{ver}.json', encoding='utf-8'))['features']
out = []
for cut in pd.date_range('2026-09-07', periods=5, freq='7D').strftime('%Y-%m-%d'):
    f = build(con, cut).drop(columns='churn')                      # 오늘 시점에는 라벨이 없다
    f['score'] = m2.predict_proba(f[feats])[:, 1]
    f['score_date'], f['model_version'] = cut, ver
    out.append(f[['score_date', 'user_id', 'score', 'model_version']])
    print(f'  {cut}: 대상 {len(f):,}명, 평균 점수 {f.score.mean():.3f}, 0.6 이상 {int((f.score >= 0.6).sum()):,}명')
scores = pd.concat(out)
scores.to_parquet('out/ds09_scores.parquet', index=False)
print(f'점수 테이블 {len(scores):,}행 → out/ds09_scores.parquet (열: {", ".join(scores.columns)})')

print('\n## 3. 드리프트 감시: PSI와 사후 성능')
def psi(expected, actual, bins=10):
    """Population Stability Index. 기준 분포를 10등분한 구간에 새 분포가 얼마나 다르게 들어가는가."""
    if expected.dtype == object or str(expected.dtype) in ('str', 'string', 'category'):
        cats = sorted(set(expected) | set(actual))
        e = np.array([(expected == c).mean() for c in cats]); a = np.array([(actual == c).mean() for c in cats])
    else:
        edges = np.unique(np.quantile(expected, np.linspace(0, 1, bins + 1))); edges[0], edges[-1] = -np.inf, np.inf
        e = np.histogram(expected, edges)[0] / len(expected); a = np.histogram(actual, edges)[0] / len(actual)
    e, a = np.clip(e, 1e-4, None), np.clip(a, 1e-4, None)
    return float(((a - e) * np.log(a / e)).sum())

base_score = m.predict_proba(tr[NUM + CAT])[:, 1]
rows = []
for cut in ['2026-06-01', '2026-07-01', '2026-08-01', '2026-09-01', '2026-10-01']:
    d = build(con, cut); p = m.predict_proba(d[NUM + CAT])[:, 1]
    rows.append({'기준일': cut, '유저': len(d), '틱톡 비율': (d.signup_channel == 'tiktok').mean(),
                 'PSI 가입채널': psi(tr.signup_channel, d.signup_channel), 'PSI tenure': psi(tr.tenure_days, d.tenure_days),
                 'PSI ses_60d': psi(tr.ses_60d, d.ses_60d), 'PSI 점수': psi(pd.Series(base_score), pd.Series(p)),
                 '실제 이탈률': d.churn.mean(), '평균 점수': p.mean(), 'AUC': roc_auc_score(d.churn, p), 'Brier': brier_score_loss(d.churn, p)})
r = pd.DataFrame(rows).set_index('기준일')
print(f'기준: {TRAIN_CUT} 학습 테이블 (틱톡 비율 {(tr.signup_channel == "tiktok").mean():.3f}, 이탈률 {tr.churn.mean():.3f})')
print(r.round(3).to_string())
print('PSI 읽는 관례: 0.1 미만 안정, 0.1~0.25 주의, 0.25 이상 큰 변화(업계에서 쓰는 경험칙이고 통계 검정은 아니다)')

print('\n신규 가입자만 보면 (가입 월별 채널 구성, 기준 = 5월 가입자)')
su = con.execute("SELECT strftime(signup_date, '%Y-%m') AS m, signup_channel FROM users WHERE signup_date >= DATE '2026-04-01'").df()
ref = su[su.m == '2026-05'].signup_channel
print(pd.DataFrame([{'가입 월': k, '가입자': len(g), '틱톡 비율': (g.signup_channel == 'tiktok').mean(), 'PSI 가입채널(5월 대비)': psi(ref, g.signup_channel)}
                    for k, g in su.groupby('m')]).round(3).to_string(index=False))

print('\n## 4. 재학습하면 나아지는가 (10/1 평가)')
te = build(con, '2026-10-01')
for cut in ['2026-05-01', '2026-07-01', '2026-09-01']:
    mm = model().fit(build(con, cut)[NUM + CAT], build(con, cut).churn)
    p = mm.predict_proba(te[NUM + CAT])[:, 1]
    print(f'  {cut} 기준 테이블로 학습 → AUC {roc_auc_score(te.churn, p):.3f}, Brier {brier_score_loss(te.churn, p):.4f}, 평균 점수 {p.mean():.3f} (실제 {te.churn.mean():.3f})')

print('\n## 5. 실험 기록: MLflow (로컬 저장소)')
try:
    import mlflow, logging, shutil
    logging.getLogger('mlflow').setLevel(logging.ERROR); logging.getLogger('alembic').setLevel(logging.ERROR)
    try:
        mlflow.set_tracking_uri('file:out/mlruns'); mlflow.set_experiment('churn')
        uri = 'file:out/mlruns'
    except Exception as e:                                           # 실제로 막힌 곳: 3.x는 파일 저장소를 거부한다
        print(f'  파일 저장소(file:out/mlruns) 실패: {type(e).__name__}: {str(e).splitlines()[0][:118]}...')
        shutil.rmtree('out/mlruns', ignore_errors=True)
        if os.path.exists('out/mlflow.db'):
            os.remove('out/mlflow.db')
        uri = 'sqlite:///out/mlflow.db'
        mlflow.set_tracking_uri(uri); mlflow.set_experiment('churn')
    print(f'  저장소: {uri}')
    te9 = build(con, '2026-09-01')
    for name, cut in [('logit_0501', '2026-05-01'), ('logit_0801', '2026-08-01')]:
        d = build(con, cut)
        with mlflow.start_run(run_name=name):
            mm = model().fit(d[NUM + CAT], d.churn); p = mm.predict_proba(te9[NUM + CAT])[:, 1]
            mlflow.log_params({'model': 'logistic', 'train_cutoff': cut, 'n_features': len(NUM + CAT), 'rows': len(d)})
            mlflow.log_metrics({'auc_0901': roc_auc_score(te9.churn, p), 'brier_0901': brier_score_loss(te9.churn, p)})
    runs = mlflow.search_runs(order_by=['start_time'])
    print(f'  mlflow {mlflow.__version__}: 실행 {len(runs)}개 기록')
    print(runs[['tags.mlflow.runName', 'params.train_cutoff', 'params.rows', 'metrics.auc_0901', 'metrics.brier_0901']].tail(2).round(4).to_string(index=False))
except Exception as e:
    print(f'  MLflow 실행 실패: {type(e).__name__}: {str(e).splitlines()[0][:160]}')
python ds/ds09_ops.py
## 1. 학습과 저장 (학습 작업)
저장: out/models/churn_logit_2026-05-01.joblib (5 KB) + 같은 이름의 .json(설명서)
{"version": "churn_logit_2026-05-01", "train_cutoff": "2026-05-01", "rows": 18438, "churn_rate": 0.336, "sklearn": "1.9.1", "train_auc": 0.7118}

## 2. 배치 스코어링 (매주 월요일 도는 작업을 5주치 흉내)
  2026-09-07: 대상 42,990명, 평균 점수 0.458, 0.6 이상 12,796명
  2026-09-14: 대상 44,395명, 평균 점수 0.463, 0.6 이상 13,673명
  2026-09-21: 대상 45,844명, 평균 점수 0.468, 0.6 이상 14,535명
  2026-09-28: 대상 47,226명, 평균 점수 0.472, 0.6 이상 15,433명
  2026-10-05: 대상 48,701명, 평균 점수 0.474, 0.6 이상 16,264명
점수 테이블 229,156행 → out/ds09_scores.parquet (열: score_date, user_id, score, model_version)

## 3. 드리프트 감시: PSI와 사후 성능
기준: 2026-05-01 학습 테이블 (틱톡 비율 0.085, 이탈률 0.336)
               유저  틱톡 비율  PSI 가입채널  PSI tenure  PSI ses_60d  PSI 점수  실제 이탈률  평균 점수    AUC  Brier
기준일                                                                                             
2026-06-01  24620  0.082     0.000       0.277        0.014   0.063   0.361  0.377  0.696  0.207
2026-07-01  29933  0.089     0.001       0.631        0.051   0.202   0.383  0.412  0.688  0.214
2026-08-01  34931  0.096     0.003       0.943        0.099   0.364   0.398  0.441  0.688  0.217
2026-09-01  41810  0.100     0.004       1.087        0.143   0.459   0.410  0.455  0.692  0.218
2026-10-01  47820  0.103     0.006       1.182        0.170   0.578   0.419  0.473  0.688  0.221
PSI 읽는 관례: 0.1 미만 안정, 0.1~0.25 주의, 0.25 이상 큰 변화(업계에서 쓰는 경험칙이고 통계 검정은 아니다)

신규 가입자만 보면 (가입 월별 채널 구성, 기준 = 5월 가입자)
   가입 월  가입자  틱톡 비율  PSI 가입채널(5월 대비)
2026-04 7312  0.092            0.001
2026-05 7545  0.089            0.000
2026-06 7041  0.141            0.031
2026-07 7369  0.139            0.040
2026-08 9357  0.142            0.032
2026-09 8532  0.140            0.027
2026-10 9521  0.135            0.024

## 4. 재학습하면 나아지는가 (10/1 평가)
  2026-05-01 기준 테이블로 학습 → AUC 0.688, Brier 0.2215, 평균 점수 0.473 (실제 0.419)
  2026-07-01 기준 테이블로 학습 → AUC 0.691, Brier 0.2166, 평균 점수 0.428 (실제 0.419)
  2026-09-01 기준 테이블로 학습 → AUC 0.692, Brier 0.2163, 평균 점수 0.422 (실제 0.419)

## 5. 실험 기록: MLflow (로컬 저장소)
  파일 저장소(file:out/mlruns) 실패: MlflowException: The filesystem tracking backend (e.g., './mlruns') is in maintenance mode and will not receive further updates. Please...
  저장소: sqlite:///out/mlflow.db
  mlflow 3.18.0: 실행 2개 기록
tags.mlflow.runName params.train_cutoff params.rows  metrics.auc_0901  metrics.brier_0901
         logit_0501          2026-05-01       18438            0.6920              0.2183
         logit_0801          2026-08-01       34931            0.6953              0.2143

1. 저장: 모델 파일에는 설명서가 따라다닌다

2. 배치 스코어링

3. 드리프트 감시

드리프트(drift)는 학습할 때와 지금의 데이터가 달라지는 일입니다. PSI(Population Stability Index)는 기준 분포를 10구간으로 나눈 뒤 새 데이터가 각 구간에 들어가는 비율이 얼마나 달라졌는지를 한 숫자로 요약합니다. 흔히 0.1 미만은 안정, 0.25 이상은 큰 변화로 읽습니다. 통계 검정이 아니라 경험칙입니다.

6월 틱톡 증액은 PSI로 잡혔을까요. 6월부터 틱톡 광고비를 늘려, 금방 떠나는 유저가 많이 들어오도록 생성기에 심어 두었습니다.

4. 재학습 기준

5. 실험 기록: MLflow에서 실제로 막힌 곳

MLflow는 "어떤 설정으로 학습해 어떤 점수가 나왔는지"를 실행마다 적어 두는 도구입니다. 엑셀에 손으로 적던 실험 표를 코드 세 줄(start_run, log_params, log_metrics)로 바꿉니다.

파일 저장소가 거부됐다

예전 예제대로 mlflow.set_tracking_uri('file:out/mlruns')를 쓰자 mlflow 3.18.0은 The filesystem tracking backend (e.g., './mlruns') is in maintenance mode 예외를 냈습니다. 영어 원문의 뜻은 "파일 저장 방식은 유지보수만 하는 상태이니 데이터베이스 방식으로 옮기라"입니다.

SQLite로 바꾸자 또 막혔다

sqlite:///out/mlflow.db로 바꾸니 UnsupportedModelRegistryStoreURIException이 났습니다. 가벼운 설치본인 mlflow-skinny에는 데이터베이스 연결 라이브러리가 빠져 있었습니다. pip install sqlalchemy alembic을 추가하자 실행 2개가 기록됐습니다. pip install mlflow(전체 설치본)를 쓰면 처음부터 들어 있습니다.

기록된 것

5월 모델과 8월 모델을 9월 1일 테이블로 평가한 AUC(0.6920, 0.6953)와 Brier 점수가 학습 기준일, 행 수와 함께 남았습니다. mlflow ui --backend-store-uri sqlite:///out/mlflow.db로 브라우저에서 볼 수 있습니다(화면은 이 교안에서 띄워 보지 않았습니다).

AI에게 시킬 때

scikit-learn 파이프라인으로 만든 이탈 모델을 주 1회 배치 스코어링으로 운영하려고 해. Airflow DAG 설계를 태스크 단위로 써줘: (1) 기준일 피처 테이블 생성 (2) 입력 검사(행 수, 결측, 피처별 PSI) (3) 모델 파일과 설명서 로드, 버전 확인 (4) 점수 테이블 적재(score_date, user_id, score, model_version) (5) 30일 전 점수의 사후 성능 계산(AUC, 평균 점수 대 실제 비율). 각 태스크가 실패했을 때 뒤 태스크와 캠페인 발송을 어떻게 할지, 그리고 재학습을 시작할 조건을 표로 정리해줘. 임계값은 예시라고 표시하고 내가 정해야 할 값은 질문으로 남겨줘.

이것만 기억하세요

모델 파일에는 설명서를, 점수 테이블에는 날짜와 모델 버전을 붙입니다. 감시는 입력 분포(PSI), 순위(AUC), 보정(평균 점수 대 실제)을 같이 보고, PSI 경보는 원인을 사람이 확인합니다.

다음
DS10. LLM을 분석에 쓰기
이어보기 →