{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ch05-000",
   "metadata": {},
   "source": [
    "# 05장 실습. 일반화와 평가\n",
    "\n",
    "**목표:** 혼동행렬·정밀도·재현율·F1·AUC를 직접 계산하고, 임계값을 목적에 맞게 고른다. 검증 오차로 모델 복잡도를 고르고, 교차검증을 직접 구현하며 데이터 누수를 피한다.\n",
    "\n",
    "- 빈칸(`# 작성하세요`)을 채우고 바로 아래 점검 셀을 실행하면 \"통과\"가 나온다.\n",
    "- 함수 문제는 **입력 배열을 바꾸지 않고** 새 값을 돌려준다.\n",
    "- 문제 3은 문제 2, 문제 5는 문제 3의 함수를 쓴다. 순서대로 푼다.\n",
    "- 막히면 `힌트`를 연다. 다 푼 뒤 `실습/해설/`의 같은 파일과 비교한다.\n",
    "- 끝나면 **커널 재시작 후 모두 실행**(Restart & Run All)으로 처음부터 통과하는지 확인한다.\n",
    "\n",
    "권장 시간: 1시간 30분. 내려받기 없이 CPU로 1분 안에 끝난다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch05-001",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 실행만 하세요\n",
    "import hashlib\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn.datasets import make_classification\n",
    "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n",
    "from sklearn.preprocessing import StandardScaler, PolynomialFeatures\n",
    "from sklearn.linear_model import LogisticRegression, LinearRegression\n",
    "from sklearn.pipeline import make_pipeline\n",
    "from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score, roc_auc_score\n",
    "\n",
    "plt.rcParams[\"font.family\"] = \"Malgun Gothic\"     # Windows 한글 글꼴\n",
    "plt.rcParams[\"axes.unicode_minus\"] = False\n",
    "\n",
    "def check(name, value, digest):\n",
    "    assert value is not None, f\"{name}: 답을 적으세요\"\n",
    "    got = hashlib.sha256(str(value).strip().upper().encode()).hexdigest()[:12]\n",
    "    assert got == digest, f\"{name}: 다시 생각해 보세요\"\n",
    "    print(name, \"통과\")\n",
    "\n",
    "# 가상의 카드 거래 데이터: 3000건, 특성 6개(단위가 제각각), 사기(1)가 약 10%\n",
    "Xc, yc = make_classification(n_samples=3000, n_features=6, n_informative=4, n_redundant=0, weights=[0.9],\n",
    "                             class_sep=1.0, flip_y=0.02, random_state=0)\n",
    "Xc = Xc * [1, 10, 100, 1000, 0.1, 5] + [0, 50, 300, 5000, 1, 20]\n",
    "Xc_tmp, Xc_te, yc_tmp, yc_te = train_test_split(Xc, yc, test_size=0.2, stratify=yc, random_state=0)\n",
    "Xc_tr, Xc_va, yc_tr, yc_va = train_test_split(Xc_tmp, yc_tmp, test_size=0.25, stratify=yc_tmp, random_state=0)\n",
    "card_model = make_pipeline(StandardScaler(), LogisticRegression()).fit(Xc_tr, yc_tr)\n",
    "p_va = card_model.predict_proba(Xc_va)[:, 1]                     # 검증 데이터의 사기 확률\n",
    "pred_va = (p_va >= 0.5).astype(int)\n",
    "\n",
    "# 다항식 과적합용 데이터(문제 7)\n",
    "r7 = np.random.default_rng(5)\n",
    "x7 = r7.uniform(-1, 1, 60)\n",
    "y7 = np.cos(2.5 * x7) + 0.5 * x7 + r7.normal(0, 0.2, 60)\n",
    "x7_tr, x7_va, y7_tr, y7_va = x7[:15], x7[15:], y7[:15], y7[15:]\n",
    "\n",
    "print(\"카드 훈련\", Xc_tr.shape, \"검증\", Xc_va.shape, \"테스트\", Xc_te.shape, \"/ 사기 비율\", round(yc.mean(), 3))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch05-002",
   "metadata": {},
   "source": [
    "## 문제 1. 분할과 과적합 참/거짓 (개념)\n",
    "\n",
    "맞으면 `O`, 틀리면 `X`. (a)~(e) 순서대로 이어 쓴 문자열을 `q1`에 적으세요. 예: `\"OXXOX\"`\n",
    "\n",
    "(a) 테스트 점수를 보고 하이퍼파라미터를 고친 뒤 다시 잰 테스트 점수는 낙관적으로 나오기 쉽다.\n",
    "(b) 훈련 오차가 검증 오차보다 훨씬 작으면 과적합을 의심한다.\n",
    "(c) 모델이 복잡할수록 검증 오차도 늘 줄어든다.\n",
    "(d) 분류에서 `stratify=y`를 쓰는 목적은 훈련 데이터의 정확도를 높이는 것이다.\n",
    "(e) 교차검증 평균이 같은 두 모델이라도 조각별 표준편차가 크면 그 평균을 덜 믿는다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch05-003",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 작성하세요\n",
    "q1 = None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch05-004",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 실행만 하세요\n",
    "check(\"q1\", q1, \"c38d8c5c8d8d\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch05-005",
   "metadata": {},
   "source": [
    "## 문제 2. 혼동행렬 칸 세기 (코드)\n",
    "\n",
    "`confusion_counts(y_true, y_pred)`를 쓰세요. 0/1 배열 두 개를 받아 `(tn, fp, fn, tp)`를 파이썬 `int` 네 개의 튜플로 돌려줍니다. sklearn은 쓰지 않습니다.\n",
    "\n",
    "<details><summary>힌트</summary>\n",
    "\n",
    "`tp = int(((y_true == 1) & (y_pred == 1)).sum())`. 나머지 세 칸도 같은 모양입니다. FP는 \"정답 0인데 예측 1\"입니다.\n",
    "</details>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch05-006",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 작성하세요\n",
    "def confusion_counts(y_true, y_pred):\n",
    "    pass   # 작성"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch05-007",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 실행만 하세요\n",
    "res = confusion_counts(np.array([0, 0, 1, 1, 1]), np.array([0, 1, 0, 1, 1]))\n",
    "assert res is not None, \"결과를 return 하세요\"\n",
    "assert isinstance(res, tuple) and len(res) == 4, f\"튜플 4개 값으로 돌려주세요(지금 {type(res).__name__})\"\n",
    "assert tuple(res) == (1, 1, 1, 2), f\"작은 예의 결과가 {res}입니다. (tn, fp, fn, tp) 순서를 확인하세요\"\n",
    "assert all(type(v) is int for v in res), \"네 값 모두 파이썬 int로 돌려주세요(int(...))\"\n",
    "yv0, pv0 = yc_va.copy(), pred_va.copy()\n",
    "got = confusion_counts(yc_va, pred_va)\n",
    "assert np.array_equal(yc_va, yv0) and np.array_equal(pred_va, pv0), \"입력 배열이 바뀌었습니다\"\n",
    "ref = tuple(int(v) for v in confusion_matrix(yc_va, pred_va).ravel())\n",
    "assert tuple(got) == ref, f\"{got} ≠ sklearn {ref}\"\n",
    "print(\"카드 검증 (tn, fp, fn, tp) =\", got)\n",
    "print(\"통과\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch05-008",
   "metadata": {},
   "source": [
    "## 문제 3. 정밀도·재현율·F1 (코드)\n",
    "\n",
    "`prf(tn, fp, fn, tp)`를 쓰세요. `(precision, recall, f1)`을 돌려줍니다.\n",
    "\n",
    "- 분모가 0이면 그 지표는 `0.0`으로 합니다(예: 1이라고 한 것이 하나도 없으면 정밀도 0.0). sklearn의 `zero_division=0`과 같습니다.\n",
    "\n",
    "<details><summary>힌트</summary>\n",
    "\n",
    "`precision = tp / (tp + fp) if tp + fp else 0.0`. F1은 `2 * p * r / (p + r)`이고, `p + r`이 0이면 0.0.\n",
    "</details>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch05-009",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 작성하세요\n",
    "def prf(tn, fp, fn, tp):\n",
    "    pass   # 작성"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch05-010",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 실행만 하세요\n",
    "res = prf(5, 1, 3, 4)\n",
    "assert res is not None, \"결과를 return 하세요\"\n",
    "assert np.allclose(res, (0.8, 4 / 7, 2 * 0.8 * (4 / 7) / (0.8 + 4 / 7))), f\"prf(5, 1, 3, 4) = {res}\"\n",
    "assert tuple(prf(10, 0, 3, 0)) == (0.0, 0.0, 0.0), \"1이라고 한 것도, 맞힌 것도 없으면 (0.0, 0.0, 0.0)이어야 합니다\"\n",
    "assert tuple(prf(10, 0, 0, 0)) == (0.0, 0.0, 0.0), \"정답 1이 하나도 없으면 재현율 분모도 0입니다\"\n",
    "r_ = np.random.default_rng(3)\n",
    "for _ in range(20):\n",
    "    yt, yp = r_.integers(0, 2, 30), r_.integers(0, 2, 30)\n",
    "    exp = (precision_score(yt, yp, zero_division=0), recall_score(yt, yp, zero_division=0), f1_score(yt, yp, zero_division=0))\n",
    "    assert np.allclose(prf(*confusion_counts(yt, yp)), exp), \"무작위 예에서 sklearn과 다릅니다\"\n",
    "p3, r3, f3 = prf(*confusion_counts(yc_va, pred_va))\n",
    "print(f\"임계값 0.5: 정밀도 {p3:.3f}, 재현율 {r3:.3f}, F1 {f3:.3f}, 정확도 {(pred_va == yc_va).mean():.3f}\")\n",
    "print(\"통과\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch05-011",
   "metadata": {},
   "source": [
    "## 문제 4. 분류·회귀 지표 참/거짓 (개념)\n",
    "\n",
    "맞으면 `O`, 틀리면 `X`. (a)~(e) 순서대로 이어 쓴 문자열을 `q4`에 적으세요.\n",
    "\n",
    "(a) 사기 거래가 1%인 데이터에서 정확도 99%면 좋은 사기 탐지 모델이다.\n",
    "(b) 같은 확률 예측에서 임계값을 낮추면 재현율은 내려가지 않는다.\n",
    "(c) `roc_auc_score`에는 `predict`가 낸 0/1 예측을 넣어야 한다.\n",
    "(d) 같은 예측에서 RMSE는 MAE보다 작을 수 없다.\n",
    "(e) 같은 모델·같은 임계값이면 정밀도는 데이터의 1 비율이 달라져도 그대로다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch05-012",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 작성하세요\n",
    "q4 = None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch05-013",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 실행만 하세요\n",
    "check(\"q4\", q4, \"42fc15e989da\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch05-014",
   "metadata": {},
   "source": [
    "## 문제 5. 목표 재현율을 만족하는 임계값 (코드)\n",
    "\n",
    "카드사가 \"사기의 **90% 이상**을 잡아야 한다\"고 정했습니다. `threshold_for_recall(y, p, target)`을 쓰세요.\n",
    "\n",
    "- 후보는 `p`에 나오는 서로 다른 값들(`np.unique(p)`)입니다. 임계값 `t`에서 예측은 `p >= t`.\n",
    "- 재현율이 `target` 이상인 후보 중 **가장 큰** 임계값을 돌려줍니다(재현율을 지키면서 잘못 경보를 가장 적게).\n",
    "- 문제 2·3의 함수를 써도 됩니다.\n",
    "\n",
    "<details><summary>힌트</summary>\n",
    "\n",
    "후보를 하나씩 돌며 `prf(*confusion_counts(y, (p >= t).astype(int)))[1] >= target`인 것만 모으고 `max`. 임계값을 낮출수록 재현율은 줄지 않으므로, 큰 쪽부터 내려오다 처음 만족하는 값을 돌려줘도 됩니다.\n",
    "</details>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch05-015",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 작성하세요\n",
    "def threshold_for_recall(y, p, target):\n",
    "    pass   # 작성"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch05-016",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 실행만 하세요\n",
    "ys, ps = np.array([1, 0, 1, 1, 0, 0, 1]), np.array([0.9, 0.8, 0.7, 0.4, 0.3, 0.2, 0.1])\n",
    "t_s = threshold_for_recall(ys, ps, 0.75)\n",
    "assert t_s is not None, \"결과를 return 하세요\"\n",
    "assert np.isclose(t_s, 0.4), f\"작은 예에서 {t_s}입니다. 재현율 0.75 이상인 가장 큰 임계값은 0.4입니다\"\n",
    "assert np.isclose(threshold_for_recall(ys, ps, 1.0), 0.1), \"재현율 1.0이 목표면 0.1이어야 합니다\"\n",
    "pv0 = p_va.copy()\n",
    "t5 = threshold_for_recall(yc_va, p_va, 0.9)\n",
    "assert np.array_equal(p_va, pv0), \"입력 배열이 바뀌었습니다\"\n",
    "cands = np.unique(p_va)\n",
    "recs = np.array([recall_score(yc_va, p_va >= t) for t in cands])\n",
    "t_ref = cands[recs >= 0.9].max()\n",
    "assert np.isclose(t5, t_ref), f\"카드 검증에서 {t5}입니다. 기대 {t_ref:.4f}\"\n",
    "pr5 = (p_va >= t5).astype(int)\n",
    "print(f\"임계값 {t5:.4f}: 재현율 {recall_score(yc_va, pr5):.3f}, 정밀도 {precision_score(yc_va, pr5):.3f}, 경보 {pr5.sum()}건 / 검증 {len(pr5)}건\")\n",
    "fig, ax = plt.subplots(figsize=(5, 3))\n",
    "ts = np.linspace(0.01, 0.9, 90)\n",
    "ax.plot(ts, [precision_score(yc_va, p_va >= t, zero_division=0) for t in ts], label=\"정밀도\")\n",
    "ax.plot(ts, [recall_score(yc_va, p_va >= t) for t in ts], label=\"재현율\")\n",
    "ax.axvline(t5, color=\"gray\", ls=\"--\"); ax.set_xlabel(\"임계값\"); ax.legend(); ax.set_title(\"카드 검증 데이터\")\n",
    "plt.show()\n",
    "print(\"통과\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch05-017",
   "metadata": {},
   "source": [
    "## 문제 6. 쌍 비교로 AUC 계산 (코드)\n",
    "\n",
    "`auc_pairs(y, score)`를 쓰세요. 정답 1인 표본과 정답 0인 표본의 **모든 쌍**에서 1의 점수가 더 높으면 1점, 같으면 0.5점, 낮으면 0점을 주고 평균을 돌려줍니다. sklearn은 쓰지 않습니다.\n",
    "\n",
    "<details><summary>힌트</summary>\n",
    "\n",
    "`pos = score[y == 1]`, `neg = score[y == 0]`. `pos[:, None] > neg[None, :]`는 `(1의 수, 0의 수)` 모양의 비교표입니다(02장 브로드캐스팅). 같음은 `==`로 따로 세어 0.5를 곱합니다.\n",
    "</details>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch05-018",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 작성하세요\n",
    "def auc_pairs(y, score):\n",
    "    pass   # 작성"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch05-019",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 실행만 하세요\n",
    "a = auc_pairs(np.array([0, 0, 1, 1]), np.array([0.1, 0.4, 0.35, 0.8]))\n",
    "assert a is not None, \"결과를 return 하세요\"\n",
    "assert np.isclose(a, 0.75), f\"작은 예에서 {a}입니다. 쌍 4개 중 3개에서 1이 높습니다\"\n",
    "assert np.isclose(auc_pairs(np.array([0, 1, 0, 1]), np.array([0.5, 0.5, 0.2, 0.9])), 0.875), \"동점 쌍은 0.5점입니다\"\n",
    "r6 = np.random.default_rng(6)\n",
    "yt, st = r6.integers(0, 2, 200), r6.integers(0, 5, 200).astype(float)     # 동점이 많은 점수\n",
    "assert np.isclose(auc_pairs(yt, st), roc_auc_score(yt, st)), \"동점이 많은 예에서 roc_auc_score와 다릅니다\"\n",
    "a6 = auc_pairs(yc_va, p_va)\n",
    "assert np.isclose(a6, roc_auc_score(yc_va, p_va)), f\"카드 검증 AUC {a6} ≠ {roc_auc_score(yc_va, p_va)}\"\n",
    "logit = card_model.decision_function(Xc_va)\n",
    "assert np.isclose(auc_pairs(yc_va, logit), a6), \"확률 대신 점수(decision_function)를 넣어도 AUC는 같아야 합니다\"\n",
    "print(\"카드 검증 AUC\", round(a6, 4), \"/ 0/1 예측을 넣으면\", round(auc_pairs(yc_va, pred_va.astype(float)), 4))\n",
    "print(\"통과\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch05-020",
   "metadata": {},
   "source": [
    "## 문제 7. 검증 오차로 차수 고르기 (코드)\n",
    "\n",
    "`degree_table(x_tr, y_tr, x_va, y_va, degrees)`를 쓰세요. 차수마다 `PolynomialFeatures(차수)` + `LinearRegression`을 **훈련 데이터로만** 맞추고, `{차수: (훈련 RMSE, 검증 RMSE)}` 딕셔너리를 돌려줍니다. 그다음 `best_degree(table)`로 검증 RMSE가 가장 작은 차수를 돌려줍니다.\n",
    "\n",
    "`x`는 1차원 배열이므로 `x[:, None]`으로 `(N, 1)`을 만들어 넣습니다.\n",
    "\n",
    "<details><summary>힌트</summary>\n",
    "\n",
    "원고 5-7절 코드. `poly = PolynomialFeatures(d).fit(x_tr[:, None])`, `m = LinearRegression().fit(poly.transform(x_tr[:, None]), y_tr)`. 검증은 `poly.transform(x_va[:, None])`. `best_degree`는 `min(table, key=lambda d: table[d][1])`.\n",
    "</details>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch05-021",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 작성하세요\n",
    "def degree_table(x_tr, y_tr, x_va, y_va, degrees):\n",
    "    pass   # 작성\n",
    "\n",
    "def best_degree(table):\n",
    "    pass   # 작성"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch05-022",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 실행만 하세요\n",
    "degs = [1, 2, 3, 4, 6, 8, 10]\n",
    "x0 = x7_tr.copy()\n",
    "tab = degree_table(x7_tr, y7_tr, x7_va, y7_va, degs)\n",
    "assert tab is not None, \"degree_table: 결과를 return 하세요\"\n",
    "assert np.array_equal(x7_tr, x0), \"입력 배열이 바뀌었습니다\"\n",
    "assert set(tab) == set(degs), f\"키가 {sorted(tab)}입니다. 차수마다 하나씩\"\n",
    "for d in degs:\n",
    "    poly = PolynomialFeatures(d).fit(x7_tr[:, None])\n",
    "    m = LinearRegression().fit(poly.transform(x7_tr[:, None]), y7_tr)\n",
    "    e_tr = np.sqrt(np.mean((m.predict(poly.transform(x7_tr[:, None])) - y7_tr) ** 2))\n",
    "    e_va = np.sqrt(np.mean((m.predict(poly.transform(x7_va[:, None])) - y7_va) ** 2))\n",
    "    assert np.allclose(tab[d], (e_tr, e_va)), f\"차수 {d}: {np.round(tab[d], 4)} ≠ 기대 ({e_tr:.4f}, {e_va:.4f}). 훈련 데이터로만 맞췄나요? RMSE(제곱근)인가요?\"\n",
    "    print(f\"차수 {d:2d}: 훈련 {tab[d][0]:.3f}  검증 {tab[d][1]:.3f}\")\n",
    "assert best_degree({1: (0.5, 0.9), 2: (0.1, 0.3), 3: (0.05, 0.6)}) == 2, \"검증 RMSE(두 번째 값)가 가장 작은 차수입니다\"\n",
    "bd = best_degree(tab)\n",
    "assert bd == min(degs, key=lambda d: tab[d][1]), f\"best_degree가 {bd}입니다\"\n",
    "assert tab[max(degs)][0] < tab[bd][0], \"가장 높은 차수의 훈련 오차가 더 작아야 합니다\"\n",
    "print(\"검증으로 고른 차수\", bd)\n",
    "print(\"통과\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch05-023",
   "metadata": {},
   "source": [
    "## 문제 8. 교차검증 직접 구현 (코드)\n",
    "\n",
    "`cv_auc(X, y, k, seed)`를 쓰세요. `StratifiedKFold(n_splits=k, shuffle=True, random_state=seed)`의 조각마다:\n",
    "\n",
    "1. 훈련 조각으로만 `StandardScaler`를 `fit`하고, 훈련·검증 조각을 그 스케일러로 변환합니다.\n",
    "2. `LogisticRegression(C=0.01)`을 훈련 조각에 학습합니다(`C`는 6장에서 다룹니다. 그대로 쓰세요).\n",
    "3. 검증 조각의 사기 확률로 `roc_auc_score`를 계산합니다.\n",
    "\n",
    "조각별 AUC를 `np.array`(길이 k)로 돌려줍니다. 결과는 `cross_val_score(make_pipeline(StandardScaler(), LogisticRegression(C=0.01)), ...)`와 같아야 합니다.\n",
    "\n",
    "<details><summary>힌트</summary>\n",
    "\n",
    "`for tr, va in StratifiedKFold(...).split(X, y):` 안에서 `sc = StandardScaler().fit(X[tr])`. 스케일러를 반복문 밖에서 전체 `X`로 맞추면 누수이고, 점검 셀이 알아챕니다.\n",
    "</details>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch05-024",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 작성하세요\n",
    "def cv_auc(X, y, k, seed):\n",
    "    pass   # 작성"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch05-025",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 실행만 하세요\n",
    "X0 = Xc_tmp.copy()\n",
    "s8 = cv_auc(Xc_tmp, yc_tmp, 5, 0)\n",
    "assert s8 is not None, \"결과를 return 하세요\"\n",
    "assert np.array_equal(Xc_tmp, X0), \"입력 배열이 바뀌었습니다\"\n",
    "assert np.shape(s8) == (5,), f\"shape가 {np.shape(s8)}입니다. 조각마다 하나씩\"\n",
    "cv8 = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)\n",
    "ref = cross_val_score(make_pipeline(StandardScaler(), LogisticRegression(C=0.01)), Xc_tmp, yc_tmp, cv=cv8, scoring=\"roc_auc\")\n",
    "leak = cross_val_score(LogisticRegression(C=0.01), StandardScaler().fit_transform(Xc_tmp), yc_tmp, cv=cv8, scoring=\"roc_auc\")\n",
    "assert not np.allclose(ref, leak, rtol=0, atol=1e-9), \"점검용 누수 계산이 정상 계산과 같습니다(점검 셀 문제)\"\n",
    "assert not np.allclose(s8, leak, rtol=0, atol=1e-9), \"스케일러를 전체 데이터로 fit한 것 같습니다. 훈련 조각으로만 fit하세요\"\n",
    "assert np.allclose(s8, ref, rtol=0, atol=1e-9), f\"{np.round(s8, 4)} ≠ cross_val_score {np.round(ref, 4)}\"\n",
    "cv3 = StratifiedKFold(n_splits=3, shuffle=True, random_state=7)\n",
    "ref3 = cross_val_score(make_pipeline(StandardScaler(), LogisticRegression(C=0.01)), Xc_tmp, yc_tmp, cv=cv3, scoring=\"roc_auc\")\n",
    "s3 = cv_auc(Xc_tmp, yc_tmp, 3, 7)\n",
    "assert np.shape(s3) == (3,) and np.allclose(s3, ref3, rtol=0, atol=1e-9), \"k=3, seed=7로 불렀을 때 결과가 다릅니다. k와 seed를 그대로 쓰세요\"\n",
    "print(\"조각별 AUC\", np.round(s8, 3), \"평균\", round(s8.mean(), 3), \"표준편차\", round(s8.std(ddof=1), 3))\n",
    "print(\"통과\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch05-026",
   "metadata": {},
   "source": [
    "## 문제 9. 너무 좋은 검증 점수 (사례)\n",
    "\n",
    "병원 팀이 흉부 X선 사진으로 폐렴을 분류했습니다. 환자 1000명에게서 사진 5000장(한 명당 여러 장)을 모아 **사진 단위로 무작위** 80 : 20으로 나눴고, 표준화는 훈련 데이터로만 했습니다. 검증 AUC는 0.99였지만, 새 환자들로 시험 운영하자 AUC가 0.75로 떨어졌습니다. 가장 알맞은 진단과 조치를 `q9`에 적으세요.\n",
    "\n",
    "- A. 학습률이 너무 크다. 학습률을 줄이고 다시 학습한다.\n",
    "- B. 같은 환자의 사진이 훈련과 검증에 나뉘어 들어가, 모델이 병이 아니라 환자를 알아보는 것으로도 맞힐 수 있었다. 환자 단위로 나누고(`GroupKFold` 등) 다시 평가한다.\n",
    "- C. 모델이 너무 단순하다. 더 큰 모델로 바꾼다.\n",
    "- D. AUC가 맞지 않는 지표다. 정확도로 다시 잰다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch05-027",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 작성하세요\n",
    "q9 = None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch05-028",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 실행만 하세요\n",
    "check(\"q9\", q9, \"df7e70e50215\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch05-029",
   "metadata": {},
   "source": [
    "## 문제 10. 상황별 지표 고르기 (사례)\n",
    "\n",
    "각 상황에서 가장 먼저 볼 지표를 고르세요. 재현율 `R`, 정밀도 `P`, AUC `A`, MAE `M`, RMSE `S`. (a)~(e) 순서대로 이어 쓴 문자열을 `q10`에 적으세요.\n",
    "\n",
    "(a) 희귀 질환 1차 선별 검사. 양성으로 나오면 정밀 검사를 하므로, 환자를 놓치는 것이 가장 나쁘다.\n",
    "(b) 메일 자동 스팸 차단. 정상 메일이 스팸함으로 가면 고객이 중요한 메일을 놓친다.\n",
    "(c) 임계값은 운영팀이 나중에 정한다. 지금은 후보 모델 세 개의 순위 매기는 능력만 비교한다.\n",
    "(d) 배달 시간 예측. 가끔 사고로 몇 시간 늦은 기록이 섞여 있고, \"평균 몇 분 틀린다\"로 설명해야 한다.\n",
    "(e) 다리 설계용 하중 예측. 대부분 잘 맞혀도 한 번 크게 틀리면 위험하다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch05-030",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 작성하세요\n",
    "q10 = None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch05-031",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 실행만 하세요\n",
    "check(\"q10\", q10, \"498f57ab7643\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch05-032",
   "metadata": {},
   "source": [
    "## 마무리\n",
    "\n",
    "- [ ] Restart & Run All로 모든 점검 셀이 \"통과\"를 출력한다.\n",
    "- [ ] 문제 5에서 목표 재현율을 0.8, 0.95로 바꿔 정밀도와 경보 건수가 어떻게 변하는지 확인했다.\n",
    "- [ ] 문제 8에서 스케일러를 반복문 밖에서 전체 데이터로 맞춰 보고, 점수가 얼마나 달라지는지 확인했다.\n",
    "- [ ] 아직 쓰지 않은 카드 **테스트** 데이터(`Xc_te`, `yc_te`)로 문제 5에서 고른 임계값의 재현율을 한 번만 재 봤다.\n",
    "- [ ] 원고 5-11절 선택 기준표의 다섯 줄을 내 말로 다시 적어 두었다.\n",
    "\n",
    "다음 장(06장)에서는 이 장에서 빌려 쓴 로지스틱 회귀가 어떻게 확률을 내는지, 그리고 과적합을 줄이는 정규화(`C`)를 다룬다."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
