{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "cffb96ae",
   "metadata": {},
   "source": [
    "# 03 실전 반도체 공정 데이터 분석 · 7~9. 전처리 · 모델 학습 · 평가\n",
    "\n",
    "- 강의 페이지: `Web/강좌/03_실전_반도체_공정_데이터분석/실전_반도체_공정_데이터분석_강의자료.html` → 목차 **전처리 · 모델 학습 · 평가**\n",
    "- 학습/테스트로 나누고 두 모델을 학습해 혼동행렬·ROC·특성 중요도로 평가합니다.\n",
    "- `fab.csv`가 이 노트북과 같은 폴더에 있어야 합니다.\n",
    "- 위에서 아래로 순서대로 실행하세요. 다른 노트북의 변수를 사용하지 않으므로 이 파일만 열어도 실행됩니다."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3c5e8e7d",
   "metadata": {},
   "source": [
    "### 7단계 · 데이터 전처리 & 분리\n",
    "- 설명: 통계 검정으로 예측에 중요한 상위 센서 컬럼을 선택합니다.\n",
    "- 수업 메모: 상위 K개 센서만 입력으로 사용"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9bfc03b2",
   "metadata": {},
   "source": [
    "### 준비 · 1~5단계 코드 실행\n",
    "\n",
    "앞 단계 코드를 그대로 모아 한 번에 실행합니다. 출력은 앞 노트북과 같습니다."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "12e6d116",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ── 1단계 ──\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "from sklearn.feature_selection import SelectKBest, f_classif   # ⭐ NEW\n",
    "from sklearn.ensemble import RandomForestClassifier\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "from sklearn.metrics import classification_report, confusion_matrix, roc_curve, auc\n",
    "\n",
    "# 그래프 한글 설정 (Mac은 'AppleGothic', Colab·리눅스는 'NanumGothic')\n",
    "plt.rcParams['font.family'] = 'Malgun Gothic'\n",
    "plt.rcParams['axes.unicode_minus'] = False\n",
    "\n",
    "# ── 2단계 ──\n",
    "df = pd.read_csv('fab.csv')\n",
    "\n",
    "# ── 3단계 결측값 처리 ──\n",
    "# 1️⃣ 컬럼별 결측률 계산\n",
    "miss_pct = (df.isnull().sum() / len(df) * 100).round(2)\n",
    "print(miss_pct.sort_values(ascending=False).head(10))\n",
    "\n",
    "# 2️⃣ 결측률 50% 초과 컬럼 제거\n",
    "THRESHOLD = 50.0\n",
    "cols_to_drop = miss_pct[miss_pct > THRESHOLD].index.tolist()\n",
    "print(f\"🗑️ 제거할 컬럼: {len(cols_to_drop)}개\")\n",
    "df = df.drop(columns=cols_to_drop)\n",
    "\n",
    "# 3️⃣ 남은 결측치는 중앙값으로 채우기 (타겟 제외!)\n",
    "numeric_cols = df.select_dtypes(include='number').columns.tolist()\n",
    "numeric_cols.remove('Pass_Fail')   # ⚠️ 타겟은 절대 채우지 말 것!\n",
    "\n",
    "df[numeric_cols] = df[numeric_cols].fillna(df[numeric_cols].median())\n",
    "print(f\"✅ 결측 처리 완료. 남은 결측: {df.isnull().sum().sum()}\")\n",
    "\n",
    "# ── 4단계 분산 0 제거 ──\n",
    "# 분산 = 0 컬럼 + 거의 0인 컬럼 모두 제거\n",
    "variances = df[numeric_cols].var()\n",
    "\n",
    "constant_cols    = variances[variances == 0].index.tolist()\n",
    "near_constant    = variances[(variances > 0) & (variances < 1e-6)].index.tolist()\n",
    "\n",
    "print(f\"분산 0  컬럼: {len(constant_cols)}개\")\n",
    "print(f\"분산 ≈0 컬럼: {len(near_constant)}개\")\n",
    "\n",
    "to_drop_var = constant_cols + near_constant\n",
    "df = df.drop(columns=to_drop_var)\n",
    "numeric_cols = [c for c in numeric_cols if c not in to_drop_var]\n",
    "\n",
    "print(f\"✅ 사용 가능한 센서: {len(numeric_cols)}개\")\n",
    "\n",
    "# ── 5단계 특성 선택 ──\n",
    "# 타겟을 0/1로 변환: 불량(1)을 양성 클래스로\n",
    "y = (df['Pass_Fail'] == 1).astype(int)\n",
    "X_all = df[numeric_cols].copy()\n",
    "\n",
    "# 상위 K=20 개 센서 자동 선택\n",
    "K = 20\n",
    "selector = SelectKBest(score_func=f_classif, k=K)\n",
    "selector.fit(X_all, y)\n",
    "\n",
    "f_scores   = pd.Series(selector.scores_, index=numeric_cols)\\\n",
    "               .replace([np.inf, -np.inf], np.nan).dropna()\n",
    "top_k_cols = f_scores.sort_values(ascending=False).head(K).index.tolist()\n",
    "\n",
    "print(f\"🏆 선택된 상위 {K}개 센서:\")\n",
    "for i, col in enumerate(top_k_cols, 1):\n",
    "    print(f\"  {i:2d}. {col}  F={f_scores[col]:6.1f}\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "87351613",
   "metadata": {},
   "outputs": [],
   "source": [
    "X = df[top_k_cols].copy()    # 상위 K개 센서만!\n",
    "# y = (df['Pass_Fail'] == 1).astype(int)  # 위에서 이미 만듦\n",
    "\n",
    "X_train, X_test, y_train, y_test = train_test_split(\n",
    "    X, y,\n",
    "    test_size=0.2,\n",
    "    random_state=42,\n",
    "    stratify=y          # ⭐ 불균형 비율 유지 필수!\n",
    ")\n",
    "\n",
    "scaler = StandardScaler()\n",
    "X_train_scaled = scaler.fit_transform(X_train)\n",
    "X_test_scaled  = scaler.transform(X_test)\n",
    "\n",
    "print(f\"학습: {X_train.shape}, 그 중 불량 {y_train.sum()}건\")\n",
    "print(f\"테스트: {X_test.shape}, 그 중 불량 {y_test.sum()}건\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8ca7a371",
   "metadata": {},
   "source": [
    "## 8단계 · 머신러닝 모델 학습"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "79b7a0bc",
   "metadata": {},
   "source": [
    "### 8단계 · 머신러닝 모델 학습\n",
    "- 설명: 전처리한 데이터로 머신러닝 모델을 학습하고 예측합니다.\n",
    "- 수업 메모: class_weight='balanced' 한 줄로 불균형 해결"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0a755fe4",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1) 로지스틱 회귀\n",
    "lr_model = LogisticRegression(\n",
    "    random_state=42, max_iter=1000,\n",
    "    class_weight='balanced'   # ⭐ 소수 클래스에 가중치\n",
    ")\n",
    "lr_model.fit(X_train_scaled, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5af77caf",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 2) 랜덤 포레스트\n",
    "rf_model = RandomForestClassifier(\n",
    "    n_estimators=200,\n",
    "    max_depth=8,\n",
    "    random_state=42,\n",
    "    class_weight='balanced'\n",
    ")\n",
    "rf_model.fit(X_train_scaled, y_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ee535d90",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 예측\n",
    "y_pred_lr = lr_model.predict(X_test_scaled)\n",
    "y_pred_rf = rf_model.predict(X_test_scaled)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b6ed646a",
   "metadata": {},
   "source": [
    "## 9단계 · 모델 평가 — Recall 최우선"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "73fdb171",
   "metadata": {},
   "source": [
    "### 9단계 · 모델 평가 — Recall 최우선\n",
    "- 설명: 전처리한 데이터로 머신러닝 모델을 학습하고 예측합니다.\n",
    "- 수업 메모: 불균형 데이터에서는 정확도가 거짓말을 합니다"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a2e44b92",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, axes = plt.subplots(1, 2, figsize=(13, 5))\n",
    "for ax, (name, model) in zip(axes,\n",
    "        [('로지스틱 회귀', lr_model), ('랜덤 포레스트', rf_model)]):\n",
    "    cm = confusion_matrix(y_test, model.predict(X_test_scaled))\n",
    "    sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', ax=ax,\n",
    "                xticklabels=['정상(0)', '불량(1)'],\n",
    "                yticklabels=['정상(0)', '불량(1)'])\n",
    "    ax.set_title(name)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dd097c29",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 상세 리포트\n",
    "print(classification_report(y_test, lr_model.predict(X_test_scaled),\n",
    "      target_names=['정상(0)', '불량(1)']))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cf6a219f",
   "metadata": {},
   "source": [
    "### 9단계 · 모델 평가 — Recall 최우선\n",
    "- 설명: 전처리한 데이터로 머신러닝 모델을 학습하고 예측합니다.\n",
    "- 수업 메모: 불균형 데이터에서는 정확도가 거짓말을 합니다"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "27ffb97d",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots(figsize=(8, 7))\n",
    "for name, model, color in [\n",
    "        ('로지스틱 회귀', lr_model, '#3498db'),\n",
    "        ('랜덤 포레스트', rf_model, '#e74c3c')]:\n",
    "    y_prob = model.predict_proba(X_test_scaled)[:, 1]\n",
    "    fpr, tpr, _ = roc_curve(y_test, y_prob)\n",
    "    roc_auc = auc(fpr, tpr)\n",
    "    ax.plot(fpr, tpr, color=color, linewidth=2.5,\n",
    "            label=f'{name} (AUC={roc_auc:.3f})')\n",
    "ax.plot([0,1], [0,1], 'k--', alpha=0.5)\n",
    "ax.set_xlabel('FPR'); ax.set_ylabel('TPR (= 불량 Recall)')\n",
    "ax.legend(); plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1bb6acd9",
   "metadata": {},
   "source": [
    "### 9단계 · 모델 평가 — Recall 최우선\n",
    "- 설명: 전처리한 데이터로 머신러닝 모델을 학습하고 예측합니다.\n",
    "- 수업 메모: 불균형 데이터에서는 정확도가 거짓말을 합니다"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "594fd6f1",
   "metadata": {},
   "outputs": [],
   "source": [
    "imp = pd.Series(rf_model.feature_importances_,\n",
    "                index=top_k_cols).sort_values()\n",
    "\n",
    "plt.figure(figsize=(10, 7))\n",
    "plt.barh(imp.index, imp.values, color='#e74c3c')\n",
    "plt.xlabel('Feature Importance')\n",
    "plt.title('랜덤 포레스트 특성 중요도')\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5db08315",
   "metadata": {},
   "source": [
    "## 마무리\n",
    "\n",
    "- `class_weight='balanced'`를 써도 모델마다 결과가 다릅니다. 이 데이터에서 랜덤 포레스트는 기본 임계값 0.5에서 불량을 하나도 잡지 못했습니다(불량 Recall 0).\n",
    "- 정확도가 아니라 **혼동행렬과 불량 Recall**로 판단하세요. 보강 실습에서 직접 확인합니다."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
