> ## Documentation Index
> Fetch the complete documentation index at: https://docs.baeum.ai.kr/llms.txt
> Use this file to discover all available pages before exploring further.

# dl-env

> 딥러닝 기본 학습, 평가, 해석 워크플로우를 위한 공통 환경입니다.

## 문서 기준

* 기준일: `2026-02-23`
* Python: `3.12`
* 운영체제: macOS, Ubuntu, Windows
* 동기화 명령: `uv sync`

## 호환성 메모

| 환경                    | PyTorch 백엔드 | 설명                                         |
| --------------------- | ----------- | ------------------------------------------ |
| Ubuntu x86\_64 (CUDA) | `cu130`     | NVIDIA GPU 학습/추론 전체 지원                     |
| macOS Apple Silicon   | `mps`       | Metal Performance Shaders 가속 (M1/M2/M3/M4) |
| macOS Intel / Windows | `cpu`       | CPU 전용, GPU 가속 없음                          |

<Note>
  `torch==2.10.0`은 OS에 관계없이 동일 버전을 설치합니다. GPU 백엔드는 시스템의 CUDA 또는 MPS 런타임에 의해 자동 결정됩니다.
</Note>

## 주요 패키지 역할

| 패키지                                    | 역할                  | 비고                   |
| -------------------------------------- | ------------------- | -------------------- |
| `torch` / `torchvision` / `torchaudio` | 딥러닝 프레임워크 핵심        | 모델 정의, 학습, 추론        |
| `scikit-learn`                         | 전통 머신러닝 알고리즘 및 전처리  | 분류, 회귀, 클러스터링, 파이프라인 |
| `xgboost` / `lightgbm`                 | 그래디언트 부스팅 앙상블       | 정형 데이터 모델링           |
| `statsmodels`                          | 통계 모델링 및 시계열 분석     | ARIMA, OLS, 가설 검정    |
| `shap`                                 | 모델 해석 (SHAP values) | 피처 중요도, 의사결정 설명      |
| `mlflow`                               | 실험 추적 및 모델 레지스트리    | 파라미터, 메트릭, 아티팩트 기록   |
| `gradio`                               | 모델 데모 웹 UI          | 빠른 프로토타입 공유          |
| `jupyterlab`                           | 인터랙티브 노트북           | 실험, EDA, 시각화         |

## pyproject.toml

```toml theme={null}
[project]
name = "dl-env"
version = "0.1.0"
description = "Deep learning baseline environment"
requires-python = "==3.12.*"
dependencies = [
  "torch==2.10.0",
  "torchvision==0.25.0",
  "torchaudio==2.10.0",
  "scikit-learn==1.8.0",
  "xgboost==3.2.0",
  "lightgbm==4.6.0",
  "statsmodels==0.14.6",
  "shap==0.50.0",
  "mlflow==3.10.0",
  "gradio==6.6.0",
  "jupyterlab==4.5.4",
  "ipykernel==7.2.0",
  "pytest==9.0.2",
  "ruff==0.15.2",
]

[tool.uv]
package = false
```

## 설치

<Steps>
  <Step title="프로젝트 생성">
    ```bash theme={null}
    uv init dl-env
    cd dl-env
    ```
  </Step>

  <Step title="의존성 락 및 동기화">
    ```bash theme={null}
    uv lock
    uv sync
    ```
  </Step>

  <Step title="Jupyter 커널 등록">
    ```bash theme={null}
    uv run python -m ipykernel install --user --name dl-env --display-name "UV dl-env"
    ```
  </Step>
</Steps>

## 설치 확인

```bash theme={null}
uv run python -c "import torch, sklearn, xgboost, lightgbm, shap; print('torch', torch.__version__); print('cuda', torch.cuda.is_available()); print('sklearn', sklearn.__version__)"
```

## 기본 사용 예시

모델 학습부터 SHAP 해석, MLflow 기록까지의 기본 워크플로우입니다.

```python theme={null}
import torch
import torch.nn as nn
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import shap
import mlflow

# 1) 데이터 준비
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
scaler = StandardScaler().fit(X_train)
X_train, X_test = scaler.transform(X_train), scaler.transform(X_test)

# 2) 모델 정의 및 학습
model = nn.Sequential(nn.Linear(4, 32), nn.ReLU(), nn.Linear(32, 3))
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
criterion = nn.CrossEntropyLoss()

for epoch in range(50):
    out = model(torch.tensor(X_train, dtype=torch.float32))
    loss = criterion(out, torch.tensor(y_train))
    optimizer.zero_grad(); loss.backward(); optimizer.step()

# 3) 평가
with torch.no_grad():
    preds = model(torch.tensor(X_test, dtype=torch.float32)).argmax(dim=1)
    acc = (preds.numpy() == y_test).mean()

# 4) SHAP 해석
explainer = shap.Explainer(lambda x: model(torch.tensor(x, dtype=torch.float32)).detach().numpy(), X_train)
shap_values = explainer(X_test[:10])

# 5) MLflow 기록
with mlflow.start_run():
    mlflow.log_param("epochs", 50)
    mlflow.log_metric("accuracy", acc)
    mlflow.pytorch.log_model(model, "model")
```

## 트러블슈팅

| 증상                                           | 원인                          | 해결                                |
| -------------------------------------------- | --------------------------- | --------------------------------- |
| `torch.cuda.is_available() == False`         | GPU 드라이버 미설치 또는 CUDA 런타임 누락 | `nvidia-smi` 확인 후 드라이버/CUDA 설치    |
| `torch.backends.mps.is_available() == False` | macOS 12.3 미만 또는 Intel Mac  | macOS 업데이트 또는 CPU 모드 사용           |
| `uv sync` 의존성 충돌                             | 기존 락 파일과 버전 불일치             | `uv lock --refresh` 후 `uv sync`   |
| SHAP 연산이 느림                                  | 대규모 데이터에 KernelExplainer 사용 | 샘플 수를 줄이거나 `TreeExplainer` 사용     |
| MLflow UI 미표시                                | 서버 미실행 상태                   | `uv run mlflow ui --port 5000` 실행 |
| `lightgbm` import 오류 (Linux)                 | `libomp` 라이브러리 누락           | `sudo apt install libomp-dev`     |

## 설치 점검 목록

* 관리자 권한/필수 도구 등 사전 요구사항을 먼저 확인했습니다.
* 설치 후 버전 확인 명령어(`--version`)를 실행해 정상 설치를 검증했습니다.
* PATH/환경변수 변경이 필요한 경우 터미널을 다시 열어 적용 여부를 확인했습니다.
* 문제가 생겼을 때를 대비해 설치 로그 또는 스크린샷을 남겼습니다.

## 관련 문서

<CardGroup cols={2}>
  <Card title="Setup 홈" icon="house" href="/setup/index">
    운영체제별 설치 흐름을 다시 확인합니다.
  </Card>

  <Card title="다음: rag-dev" icon="arrow-right" href="/setup/uv-env/rag-dev">
    다음 설치 단계를 이어서 진행합니다.
  </Card>
</CardGroup>
