DOCS/journey/ideas/250808_7감정_학습_가이드.md
Claude-51124 22557e7132 docs: 오래된 트러블슈팅 아카이브 및 구조 정리
- 7-8월 초기 구축 문서 12개를 _archive/troubleshooting/2025_07-08_initial_setup/로 이동
- book/300_architecture/390_human_in_the_loop_intent_learning.md를 journey/research/intent_classification/로 이동 (개발 여정 문서)
- 빈 폴더 제거 (journey/assets/*)
2025-11-17 14:06:05 +09:00

176 lines
3.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 한국어 7감정 분류 모델 학습 가이드
작성일: 2025년 8월 8일
작성자: happybell80 & Claude
## 개요
AI Hub 표준 7개 감정(Ekman 기반) 분류 모델 학습을 위한 가이드입니다.
## 7개 감정 카테고리
```
fear, surprise, anger, sadness, neutral, happiness, disgust
```
## 데이터 준비
### CSV 형식
```csv
text,label
"오늘 정말 기분이 좋아요!",happiness
"갑자기 놀랐어요",surprise
"너무 화가 나요",anger
```
### 파일 구조
```
data/
├── train.csv # 학습 데이터
├── val.csv # 검증 데이터
└── test.csv # 테스트 데이터
```
## 학습 명령어
### 단일 GPU (RTX 3060)
```bash
python train_korean_emotion.py \
--model_name klue/bert-base \
--train_csv data/train.csv \
--val_csv data/val.csv \
--test_csv data/test.csv \
--output_dir outputs/kemo-bert-base \
--epochs 4 \
--batch_size 32 \
--max_len 128 \
--lr 2e-5 \
--fp16
```
### 멀티 GPU (2×RTX 3060)
```bash
accelerate launch train_korean_emotion.py \
--model_name klue/bert-base \
--train_csv data/train.csv \
--val_csv data/val.csv \
--test_csv data/test.csv \
--output_dir outputs/kemo-bert-base \
--epochs 4 \
--batch_size 32 \
--max_len 128 \
--lr 2e-5 \
--fp16
```
## 예상 학습 시간
### 하드웨어: i9 + 32GB RAM + RTX 3060 12GB × 2
- **단일 GPU**: 3 epochs 25-45분, 5 epochs 45-75분
- **듀얼 GPU**: 3 epochs 15-30분, 5 epochs 30-50분
## 주요 옵션
- `--use_class_weights`: 클래스 불균형 완화
- `--export_onnx`: ONNX 변환만 실행
- `--fp16`: 혼합 정밀도 학습 (메모리 절약)
## 산출물
```
outputs/kemo-bert-base/
├── pytorch_model.bin # 학습된 모델
├── config.json # 모델 설정
├── tokenizer_config.json # 토크나이저 설정
├── calibration.json # 온도 보정값
├── metrics.json # 성능 지표
└── model.onnx # ONNX 변환 (자동)
```
## 핵심 특징
### 1. 온도 보정 (Temperature Scaling)
- 검증 데이터로 자동 캘리브레이션
- 과신뢰 문제 해결
- `calibration.json`에 최적 온도 저장
### 2. 평가 지표
- **Macro F1**: 클래스별 균형 성능
- **ECE**: 신뢰도 캘리브레이션 오차
- **Brier Score**: 확률 예측 정확도
### 3. ONNX 자동 변환
- 학습 완료 후 자동 변환 시도
- 실패 시 `--export_onnx`로 재실행
## 51124 서버 연동
### 1. 로컬에서 학습 완료 후
```bash
# 모델 파일 압축
tar -czf kemo-bert-base.tar.gz outputs/kemo-bert-base/
```
### 2. 51124 서버로 전송
```bash
scp kemo-bert-base.tar.gz admin@51124:/home/admin/ivada_project/
```
### 3. 서버에서 ONNX 검증
```python
# 이미 .onnx 파일이 있으면 바로 사용
# 없으면 서버에서 변환
python convert_to_onnx.py --model_dir outputs/kemo-bert-base
```
## 추론 시 온도 보정 적용
```python
import json
import torch
# 캘리브레이션 로드
with open("calibration.json") as f:
T = json.load(f)["temperature"]
# 추론
logits = model(inputs)
calibrated_logits = logits / T
probs = torch.softmax(calibrated_logits, dim=-1)
```
## AI Hub 데이터 변환 예시
```python
import pandas as pd
# AI Hub 형식 → 학습 형식
df = pd.read_csv("aihub_emotion.csv")
df_train = pd.DataFrame({
"text": df["sentence"],
"label": df["emotion"].str.lower() # 소문자 변환
})
df_train.to_csv("data/train.csv", index=False)
```
## 문제 해결
### CUDA Out of Memory
- `--batch_size` 줄이기 (32 → 16)
- `--max_len` 줄이기 (128 → 64)
- `--fp16` 추가
### ONNX 변환 실패
```bash
# 별도 실행
python train_korean_emotion.py \
--export_onnx \
--output_dir outputs/kemo-bert-base
```
## 참고사항
- **모델 선택**: `klue/bert-base` 권장 (한국어 특화)
- **데이터 크기**: 39,000 문장 기준
- **최적 epochs**: 3-5 (과적합 주의)
- **학습률**: 2e-5 (BERT 계열 표준)