Add YOLO training and evaluation scripts
Browse files- Add split_train_val.py: Train/Val 8:2 분할 스크립트
- Add train_yolo.py: YOLOv8 모델 학습 스크립트 (100 epochs)
- Add quick_train.py: 빠른 테스트 학습 (5 epochs)
- Add evaluate.py: 모델 성능 평가 및 시각화
- Add inference.py: 추론 테스트 스크립트
- Update requirements.txt: 필요 패키지 추가
- Update README.md: 학습 프로세스 가이드 추가
- Update .gitignore: 학습 결과 디렉토리 제외
Features:
- Train/Validation split for proper model evaluation
- Comprehensive evaluation with confusion matrix
- Class-wise performance analysis
- Inference testing with visualization
- .gitignore +13 -0
- README.md +58 -0
- evaluate.py +323 -0
- inference.py +240 -0
- quick_train.py +26 -0
- requirements.txt +19 -0
- split_train_val.py +226 -0
- train_yolo.py +233 -0
.gitignore
CHANGED
|
@@ -29,3 +29,16 @@ Thumbs.db
|
|
| 29 |
# Temporary files
|
| 30 |
*.tmp
|
| 31 |
*.temp
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
# Temporary files
|
| 30 |
*.tmp
|
| 31 |
*.temp
|
| 32 |
+
|
| 33 |
+
# YOLO training outputs
|
| 34 |
+
runs/
|
| 35 |
+
waste_classification/
|
| 36 |
+
test_run/
|
| 37 |
+
dataset_split/
|
| 38 |
+
evaluation_results/
|
| 39 |
+
*.pt
|
| 40 |
+
*.onnx
|
| 41 |
+
|
| 42 |
+
# Cached files
|
| 43 |
+
__pycache__/
|
| 44 |
+
*.pyc
|
README.md
CHANGED
|
@@ -62,13 +62,71 @@ size_categories:
|
|
| 62 |
│ ├── classes.txt
|
| 63 |
│ ├── classes_kr.txt
|
| 64 |
│ └── data.yaml
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
├── coco_to_yolo.py # COCO → YOLO 변환 스크립트
|
| 66 |
├── remap_to_5_classes.py # 60개 → 5개 재분류 스크립트
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
└── README.md
|
| 68 |
```
|
| 69 |
|
| 70 |
## 사용 방법
|
| 71 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
### YOLOv8 학습 예시 (5개 클래스)
|
| 73 |
|
| 74 |
```python
|
|
|
|
| 62 |
│ ├── classes.txt
|
| 63 |
│ ├── classes_kr.txt
|
| 64 |
│ └── data.yaml
|
| 65 |
+
├── dataset_split/ # Train/Val 분할 데이터 (실행 후 생성)
|
| 66 |
+
│ ├── images/
|
| 67 |
+
│ │ ├── train/ # 1,200개 (80%)
|
| 68 |
+
│ │ └── val/ # 300개 (20%)
|
| 69 |
+
│ ├── labels/
|
| 70 |
+
│ │ ├── train/
|
| 71 |
+
│ │ └── val/
|
| 72 |
+
│ └── data.yaml
|
| 73 |
├── coco_to_yolo.py # COCO → YOLO 변환 스크립트
|
| 74 |
├── remap_to_5_classes.py # 60개 → 5개 재분류 스크립트
|
| 75 |
+
├── split_train_val.py # Train/Val 분할 스크립트
|
| 76 |
+
├── train_yolo.py # 모델 학습 스크립트
|
| 77 |
+
├── quick_train.py # 빠른 테스트 학습
|
| 78 |
+
├── evaluate.py # 모델 평가 스크립트
|
| 79 |
+
├── inference.py # 추론 테스트 스크립트
|
| 80 |
+
├── requirements.txt # 필요 패키지
|
| 81 |
└── README.md
|
| 82 |
```
|
| 83 |
|
| 84 |
## 사용 방법
|
| 85 |
|
| 86 |
+
### 전체 학습 프로세스
|
| 87 |
+
|
| 88 |
+
#### 1단계: 환경 설치
|
| 89 |
+
|
| 90 |
+
```bash
|
| 91 |
+
pip install -r requirements.txt
|
| 92 |
+
```
|
| 93 |
+
|
| 94 |
+
#### 2단계: 데이터 분할 (Train 80% / Val 20%)
|
| 95 |
+
|
| 96 |
+
```bash
|
| 97 |
+
python split_train_val.py
|
| 98 |
+
```
|
| 99 |
+
|
| 100 |
+
이 스크립트는 데이터를 Train/Validation으로 8:2 비율로 분할하고 `dataset_split/` 디렉토리를 생성합니다.
|
| 101 |
+
|
| 102 |
+
#### 3단계: 모델 학습
|
| 103 |
+
|
| 104 |
+
```bash
|
| 105 |
+
# 빠른 테스트 (5 에포크)
|
| 106 |
+
python quick_train.py
|
| 107 |
+
|
| 108 |
+
# 본격 학습 (100 에포크)
|
| 109 |
+
python train_yolo.py
|
| 110 |
+
```
|
| 111 |
+
|
| 112 |
+
#### 4단계: 모델 평가
|
| 113 |
+
|
| 114 |
+
```bash
|
| 115 |
+
python evaluate.py waste_classification/yolov8n_5class/weights/best.pt
|
| 116 |
+
```
|
| 117 |
+
|
| 118 |
+
이 스크립트는 다음을 생성합니다:
|
| 119 |
+
- 혼동 행렬 (Confusion Matrix)
|
| 120 |
+
- 클래스별 성능 분석 그래프
|
| 121 |
+
- 상세 분류 리포트
|
| 122 |
+
- JSON 결과 파일
|
| 123 |
+
|
| 124 |
+
#### 5단계: 추론 테스트
|
| 125 |
+
|
| 126 |
+
```bash
|
| 127 |
+
python inference.py waste_classification/yolov8n_5class/weights/best.pt data/batch_1/000006.jpg
|
| 128 |
+
```
|
| 129 |
+
|
| 130 |
### YOLOv8 학습 예시 (5개 클래스)
|
| 131 |
|
| 132 |
```python
|
evaluate.py
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
학습된 모델 성능 평가 스크립트
|
| 3 |
+
- Validation 데이터로 상세 평가
|
| 4 |
+
- 클래스별 성능 분석
|
| 5 |
+
- 혼동 행렬, PR 곡선 등 시각화
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from ultralytics import YOLO
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
import json
|
| 11 |
+
import matplotlib.pyplot as plt
|
| 12 |
+
import seaborn as sns
|
| 13 |
+
import numpy as np
|
| 14 |
+
from sklearn.metrics import classification_report, confusion_matrix
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def evaluate_model(model_path, data_yaml='dataset_split/data.yaml', save_dir='evaluation_results'):
|
| 18 |
+
"""
|
| 19 |
+
모델 상세 평가
|
| 20 |
+
|
| 21 |
+
Args:
|
| 22 |
+
model_path: 학습된 모델 경로 (.pt 파일)
|
| 23 |
+
data_yaml: 데이터셋 설정 파일
|
| 24 |
+
save_dir: 결과 저장 디렉토리
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
print("=" * 70)
|
| 28 |
+
print("모델 성능 평가")
|
| 29 |
+
print("=" * 70)
|
| 30 |
+
|
| 31 |
+
# 모델 로드
|
| 32 |
+
print(f"\n모델 로드: {model_path}")
|
| 33 |
+
model = YOLO(model_path)
|
| 34 |
+
|
| 35 |
+
# 저장 디렉토리 생성
|
| 36 |
+
save_path = Path(save_dir)
|
| 37 |
+
save_path.mkdir(exist_ok=True)
|
| 38 |
+
|
| 39 |
+
# ========================================
|
| 40 |
+
# 1. 전체 Validation 평가
|
| 41 |
+
# ========================================
|
| 42 |
+
print("\n" + "=" * 70)
|
| 43 |
+
print("1. Validation 데이터셋 평가")
|
| 44 |
+
print("=" * 70)
|
| 45 |
+
|
| 46 |
+
metrics = model.val(
|
| 47 |
+
data=data_yaml,
|
| 48 |
+
split='val',
|
| 49 |
+
save_json=True,
|
| 50 |
+
save_hybrid=True,
|
| 51 |
+
conf=0.001,
|
| 52 |
+
iou=0.6,
|
| 53 |
+
max_det=300,
|
| 54 |
+
plots=True,
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
# 전체 성능 출력
|
| 58 |
+
print("\n📊 전체 성능 지표:")
|
| 59 |
+
print(f" mAP50 : {metrics.box.map50:.4f} (50% IoU에서 정확도)")
|
| 60 |
+
print(f" mAP50-95 : {metrics.box.map:.4f} (50-95% IoU 평균)")
|
| 61 |
+
print(f" Precision : {metrics.box.mp:.4f} (정밀도)")
|
| 62 |
+
print(f" Recall : {metrics.box.mr:.4f} (재현율)")
|
| 63 |
+
|
| 64 |
+
# 클래스별 성능
|
| 65 |
+
print("\n📋 클래스별 성능:")
|
| 66 |
+
print(f"{'Class':<15} {'mAP50':>8} {'mAP50-95':>10} {'Precision':>10} {'Recall':>8}")
|
| 67 |
+
print("-" * 65)
|
| 68 |
+
|
| 69 |
+
class_names = ['Plastic', 'Vinyl', 'Can', 'Glass', 'Paper']
|
| 70 |
+
|
| 71 |
+
for i, name in enumerate(class_names):
|
| 72 |
+
if i < len(metrics.box.ap50):
|
| 73 |
+
map50 = metrics.box.ap50[i]
|
| 74 |
+
map50_95 = metrics.box.ap[i]
|
| 75 |
+
precision = metrics.box.p[i] if i < len(metrics.box.p) else 0
|
| 76 |
+
recall = metrics.box.r[i] if i < len(metrics.box.r) else 0
|
| 77 |
+
|
| 78 |
+
print(f"{name:<15} {map50:>8.4f} {map50_95:>10.4f} {precision:>10.4f} {recall:>8.4f}")
|
| 79 |
+
|
| 80 |
+
# ========================================
|
| 81 |
+
# 2. 상세 분석 - 예측 결과 수집
|
| 82 |
+
# ========================================
|
| 83 |
+
print("\n" + "=" * 70)
|
| 84 |
+
print("2. 상세 분석 - Validation 이미지 예측")
|
| 85 |
+
print("=" * 70)
|
| 86 |
+
|
| 87 |
+
# Validation 이미지 경로 읽기
|
| 88 |
+
val_txt = Path('dataset_split/val.txt')
|
| 89 |
+
if val_txt.exists():
|
| 90 |
+
with open(val_txt, 'r') as f:
|
| 91 |
+
val_images = [line.strip() for line in f.readlines()]
|
| 92 |
+
else:
|
| 93 |
+
# val.txt가 없으면 직접 찾기
|
| 94 |
+
val_images_dir = Path('dataset_split/images/val')
|
| 95 |
+
val_images = list(val_images_dir.glob('**/*.[jJ][pP][gG]'))
|
| 96 |
+
|
| 97 |
+
print(f"Validation 이미지 수: {len(val_images)}")
|
| 98 |
+
|
| 99 |
+
# 예측 결과 수집
|
| 100 |
+
all_true_labels = []
|
| 101 |
+
all_pred_labels = []
|
| 102 |
+
all_confidences = []
|
| 103 |
+
|
| 104 |
+
print("예측 진행 중...")
|
| 105 |
+
for img_path in val_images[:100]: # 일부만 샘플링 (시간 절약)
|
| 106 |
+
# 예측
|
| 107 |
+
results = model.predict(img_path, verbose=False, conf=0.25)
|
| 108 |
+
|
| 109 |
+
# Ground Truth 레이블 읽기
|
| 110 |
+
label_path = str(img_path).replace('/images/', '/labels/').replace('\\images\\', '\\labels\\')
|
| 111 |
+
label_path = label_path.replace('.jpg', '.txt').replace('.JPG', '.txt')
|
| 112 |
+
|
| 113 |
+
if Path(label_path).exists():
|
| 114 |
+
with open(label_path, 'r') as f:
|
| 115 |
+
for line in f:
|
| 116 |
+
parts = line.strip().split()
|
| 117 |
+
if len(parts) >= 5:
|
| 118 |
+
true_class = int(parts[0])
|
| 119 |
+
all_true_labels.append(true_class)
|
| 120 |
+
|
| 121 |
+
# 예측 결과
|
| 122 |
+
for r in results:
|
| 123 |
+
for box in r.boxes:
|
| 124 |
+
pred_class = int(box.cls[0])
|
| 125 |
+
conf = float(box.conf[0])
|
| 126 |
+
all_pred_labels.append(pred_class)
|
| 127 |
+
all_confidences.append(conf)
|
| 128 |
+
|
| 129 |
+
# ========================================
|
| 130 |
+
# 3. 혼동 행렬 (Confusion Matrix)
|
| 131 |
+
# ========================================
|
| 132 |
+
print("\n" + "=" * 70)
|
| 133 |
+
print("3. 혼동 행렬 생성")
|
| 134 |
+
print("=" * 70)
|
| 135 |
+
|
| 136 |
+
if len(all_true_labels) > 0 and len(all_pred_labels) > 0:
|
| 137 |
+
# 길이 맞추기
|
| 138 |
+
min_len = min(len(all_true_labels), len(all_pred_labels))
|
| 139 |
+
all_true_labels = all_true_labels[:min_len]
|
| 140 |
+
all_pred_labels = all_pred_labels[:min_len]
|
| 141 |
+
|
| 142 |
+
# Confusion Matrix
|
| 143 |
+
cm = confusion_matrix(all_true_labels, all_pred_labels, labels=range(5))
|
| 144 |
+
|
| 145 |
+
# 시각화
|
| 146 |
+
plt.figure(figsize=(10, 8))
|
| 147 |
+
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',
|
| 148 |
+
xticklabels=class_names,
|
| 149 |
+
yticklabels=class_names)
|
| 150 |
+
plt.title('Confusion Matrix', fontsize=16, fontweight='bold')
|
| 151 |
+
plt.ylabel('True Label', fontsize=12)
|
| 152 |
+
plt.xlabel('Predicted Label', fontsize=12)
|
| 153 |
+
plt.tight_layout()
|
| 154 |
+
|
| 155 |
+
cm_path = save_path / 'confusion_matrix_detailed.png'
|
| 156 |
+
plt.savefig(cm_path, dpi=300, bbox_inches='tight')
|
| 157 |
+
print(f"✅ 혼동 행렬 저장: {cm_path}")
|
| 158 |
+
plt.close()
|
| 159 |
+
|
| 160 |
+
# Classification Report
|
| 161 |
+
print("\n📊 Classification Report:")
|
| 162 |
+
report = classification_report(
|
| 163 |
+
all_true_labels,
|
| 164 |
+
all_pred_labels,
|
| 165 |
+
target_names=class_names,
|
| 166 |
+
digits=4
|
| 167 |
+
)
|
| 168 |
+
print(report)
|
| 169 |
+
|
| 170 |
+
# 리포트 저장
|
| 171 |
+
with open(save_path / 'classification_report.txt', 'w') as f:
|
| 172 |
+
f.write(report)
|
| 173 |
+
|
| 174 |
+
# ========================================
|
| 175 |
+
# 4. 성능 분석 그래프
|
| 176 |
+
# ========================================
|
| 177 |
+
print("\n" + "=" * 70)
|
| 178 |
+
print("4. 성능 분석 그래프 생성")
|
| 179 |
+
print("=" * 70)
|
| 180 |
+
|
| 181 |
+
# 클래스별 mAP 비교
|
| 182 |
+
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
|
| 183 |
+
|
| 184 |
+
# (1) 클래스별 mAP50
|
| 185 |
+
ax1 = axes[0, 0]
|
| 186 |
+
map50_values = [metrics.box.ap50[i] if i < len(metrics.box.ap50) else 0
|
| 187 |
+
for i in range(5)]
|
| 188 |
+
colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A', '#98D8C8']
|
| 189 |
+
bars1 = ax1.bar(class_names, map50_values, color=colors, alpha=0.7, edgecolor='black')
|
| 190 |
+
ax1.set_ylabel('mAP50', fontsize=12, fontweight='bold')
|
| 191 |
+
ax1.set_title('클래스별 mAP50', fontsize=14, fontweight='bold')
|
| 192 |
+
ax1.set_ylim(0, 1)
|
| 193 |
+
ax1.grid(axis='y', alpha=0.3)
|
| 194 |
+
|
| 195 |
+
# 값 표시
|
| 196 |
+
for bar in bars1:
|
| 197 |
+
height = bar.get_height()
|
| 198 |
+
ax1.text(bar.get_x() + bar.get_width()/2., height,
|
| 199 |
+
f'{height:.3f}', ha='center', va='bottom', fontsize=10)
|
| 200 |
+
|
| 201 |
+
# (2) 클래스별 mAP50-95
|
| 202 |
+
ax2 = axes[0, 1]
|
| 203 |
+
map50_95_values = [metrics.box.ap[i] if i < len(metrics.box.ap) else 0
|
| 204 |
+
for i in range(5)]
|
| 205 |
+
bars2 = ax2.bar(class_names, map50_95_values, color=colors, alpha=0.7, edgecolor='black')
|
| 206 |
+
ax2.set_ylabel('mAP50-95', fontsize=12, fontweight='bold')
|
| 207 |
+
ax2.set_title('클래스별 mAP50-95', fontsize=14, fontweight='bold')
|
| 208 |
+
ax2.set_ylim(0, 1)
|
| 209 |
+
ax2.grid(axis='y', alpha=0.3)
|
| 210 |
+
|
| 211 |
+
for bar in bars2:
|
| 212 |
+
height = bar.get_height()
|
| 213 |
+
ax2.text(bar.get_x() + bar.get_width()/2., height,
|
| 214 |
+
f'{height:.3f}', ha='center', va='bottom', fontsize=10)
|
| 215 |
+
|
| 216 |
+
# (3) Precision vs Recall
|
| 217 |
+
ax3 = axes[1, 0]
|
| 218 |
+
precision_values = [metrics.box.p[i] if i < len(metrics.box.p) else 0
|
| 219 |
+
for i in range(5)]
|
| 220 |
+
recall_values = [metrics.box.r[i] if i < len(metrics.box.r) else 0
|
| 221 |
+
for i in range(5)]
|
| 222 |
+
|
| 223 |
+
x = np.arange(len(class_names))
|
| 224 |
+
width = 0.35
|
| 225 |
+
ax3.bar(x - width/2, precision_values, width, label='Precision',
|
| 226 |
+
color='skyblue', alpha=0.8, edgecolor='black')
|
| 227 |
+
ax3.bar(x + width/2, recall_values, width, label='Recall',
|
| 228 |
+
color='lightcoral', alpha=0.8, edgecolor='black')
|
| 229 |
+
ax3.set_ylabel('Score', fontsize=12, fontweight='bold')
|
| 230 |
+
ax3.set_title('Precision vs Recall', fontsize=14, fontweight='bold')
|
| 231 |
+
ax3.set_xticks(x)
|
| 232 |
+
ax3.set_xticklabels(class_names)
|
| 233 |
+
ax3.legend()
|
| 234 |
+
ax3.set_ylim(0, 1)
|
| 235 |
+
ax3.grid(axis='y', alpha=0.3)
|
| 236 |
+
|
| 237 |
+
# (4) F1-Score
|
| 238 |
+
ax4 = axes[1, 1]
|
| 239 |
+
f1_scores = [2 * (p * r) / (p + r) if (p + r) > 0 else 0
|
| 240 |
+
for p, r in zip(precision_values, recall_values)]
|
| 241 |
+
bars4 = ax4.bar(class_names, f1_scores, color=colors, alpha=0.7, edgecolor='black')
|
| 242 |
+
ax4.set_ylabel('F1-Score', fontsize=12, fontweight='bold')
|
| 243 |
+
ax4.set_title('클래스별 F1-Score', fontsize=14, fontweight='bold')
|
| 244 |
+
ax4.set_ylim(0, 1)
|
| 245 |
+
ax4.grid(axis='y', alpha=0.3)
|
| 246 |
+
|
| 247 |
+
for bar in bars4:
|
| 248 |
+
height = bar.get_height()
|
| 249 |
+
ax4.text(bar.get_x() + bar.get_width()/2., height,
|
| 250 |
+
f'{height:.3f}', ha='center', va='bottom', fontsize=10)
|
| 251 |
+
|
| 252 |
+
plt.tight_layout()
|
| 253 |
+
performance_path = save_path / 'performance_analysis.png'
|
| 254 |
+
plt.savefig(performance_path, dpi=300, bbox_inches='tight')
|
| 255 |
+
print(f"✅ 성능 분석 그래프 저장: {performance_path}")
|
| 256 |
+
plt.close()
|
| 257 |
+
|
| 258 |
+
# ========================================
|
| 259 |
+
# 5. 결과 JSON 저장
|
| 260 |
+
# ========================================
|
| 261 |
+
results_dict = {
|
| 262 |
+
'overall': {
|
| 263 |
+
'mAP50': float(metrics.box.map50),
|
| 264 |
+
'mAP50_95': float(metrics.box.map),
|
| 265 |
+
'precision': float(metrics.box.mp),
|
| 266 |
+
'recall': float(metrics.box.mr),
|
| 267 |
+
},
|
| 268 |
+
'per_class': {}
|
| 269 |
+
}
|
| 270 |
+
|
| 271 |
+
for i, name in enumerate(class_names):
|
| 272 |
+
if i < len(metrics.box.ap50):
|
| 273 |
+
results_dict['per_class'][name] = {
|
| 274 |
+
'mAP50': float(metrics.box.ap50[i]),
|
| 275 |
+
'mAP50_95': float(metrics.box.ap[i]),
|
| 276 |
+
'precision': float(metrics.box.p[i]) if i < len(metrics.box.p) else 0,
|
| 277 |
+
'recall': float(metrics.box.r[i]) if i < len(metrics.box.r) else 0,
|
| 278 |
+
'f1_score': f1_scores[i],
|
| 279 |
+
}
|
| 280 |
+
|
| 281 |
+
json_path = save_path / 'evaluation_results.json'
|
| 282 |
+
with open(json_path, 'w', encoding='utf-8') as f:
|
| 283 |
+
json.dump(results_dict, f, indent=2, ensure_ascii=False)
|
| 284 |
+
|
| 285 |
+
print(f"✅ 결과 JSON 저장: {json_path}")
|
| 286 |
+
|
| 287 |
+
# ========================================
|
| 288 |
+
# 최종 요약
|
| 289 |
+
# ========================================
|
| 290 |
+
print("\n" + "=" * 70)
|
| 291 |
+
print("평가 완료!")
|
| 292 |
+
print("=" * 70)
|
| 293 |
+
print(f"\n저장 위치: {save_path.absolute()}")
|
| 294 |
+
print("\n생성된 파일:")
|
| 295 |
+
print(f" - confusion_matrix_detailed.png")
|
| 296 |
+
print(f" - performance_analysis.png")
|
| 297 |
+
print(f" - classification_report.txt")
|
| 298 |
+
print(f" - evaluation_results.json")
|
| 299 |
+
|
| 300 |
+
return metrics, results_dict
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
if __name__ == '__main__':
|
| 304 |
+
import sys
|
| 305 |
+
|
| 306 |
+
# 모델 경로 입력
|
| 307 |
+
if len(sys.argv) > 1:
|
| 308 |
+
model_path = sys.argv[1]
|
| 309 |
+
else:
|
| 310 |
+
# 기본값: 최신 학습 모델
|
| 311 |
+
default_path = 'waste_classification/yolov8n_5class/weights/best.pt'
|
| 312 |
+
|
| 313 |
+
print(f"모델 경로를 입력하세요 (엔터: {default_path}):")
|
| 314 |
+
user_input = input().strip()
|
| 315 |
+
model_path = user_input if user_input else default_path
|
| 316 |
+
|
| 317 |
+
# 모델 존재 확인
|
| 318 |
+
if not Path(model_path).exists():
|
| 319 |
+
print(f"❌ 모델 파일을 찾을 수 없습니다: {model_path}")
|
| 320 |
+
sys.exit(1)
|
| 321 |
+
|
| 322 |
+
# 평가 실행
|
| 323 |
+
evaluate_model(model_path)
|
inference.py
ADDED
|
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
학습된 모델로 추론 (예측) 테스트
|
| 3 |
+
- 단일 이미지 또는 폴더 예측
|
| 4 |
+
- 결과 시각화 및 저장
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from ultralytics import YOLO
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
import cv2
|
| 10 |
+
import matplotlib.pyplot as plt
|
| 11 |
+
from PIL import Image
|
| 12 |
+
import numpy as np
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def predict_image(model_path, image_path, conf=0.25, save=True, show=False):
|
| 16 |
+
"""
|
| 17 |
+
이미지 예측
|
| 18 |
+
|
| 19 |
+
Args:
|
| 20 |
+
model_path: 모델 경로
|
| 21 |
+
image_path: 이미지 경로
|
| 22 |
+
conf: 신뢰도 임계값 (0.0 ~ 1.0)
|
| 23 |
+
save: 결과 저장 여부
|
| 24 |
+
show: 결과 표시 여부
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
print("=" * 60)
|
| 28 |
+
print("이미지 예측")
|
| 29 |
+
print("=" * 60)
|
| 30 |
+
|
| 31 |
+
# 모델 로드
|
| 32 |
+
print(f"모델 로드: {model_path}")
|
| 33 |
+
model = YOLO(model_path)
|
| 34 |
+
|
| 35 |
+
# 예측
|
| 36 |
+
print(f"이미지: {image_path}")
|
| 37 |
+
print(f"신뢰도 임계값: {conf}")
|
| 38 |
+
|
| 39 |
+
results = model.predict(
|
| 40 |
+
source=image_path,
|
| 41 |
+
save=save,
|
| 42 |
+
conf=conf,
|
| 43 |
+
iou=0.7,
|
| 44 |
+
show_labels=True,
|
| 45 |
+
show_conf=True,
|
| 46 |
+
line_width=2,
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
# 결과 분석
|
| 50 |
+
for r in results:
|
| 51 |
+
print(f"\n탐지 결과:")
|
| 52 |
+
print(f" 이미지 크기: {r.orig_shape}")
|
| 53 |
+
print(f" 탐지된 객체 수: {len(r.boxes)}")
|
| 54 |
+
|
| 55 |
+
if len(r.boxes) > 0:
|
| 56 |
+
print(f"\n {'클래스':<12} {'신뢰도':>8} {'좌표 (x, y, w, h)'}")
|
| 57 |
+
print(" " + "-" * 50)
|
| 58 |
+
|
| 59 |
+
for box in r.boxes:
|
| 60 |
+
cls_id = int(box.cls[0])
|
| 61 |
+
conf_val = float(box.conf[0])
|
| 62 |
+
cls_name = r.names[cls_id]
|
| 63 |
+
xyxy = box.xyxy[0].cpu().numpy()
|
| 64 |
+
|
| 65 |
+
print(f" {cls_name:<12} {conf_val:>7.2%} "
|
| 66 |
+
f"({xyxy[0]:.0f}, {xyxy[1]:.0f}, "
|
| 67 |
+
f"{xyxy[2]-xyxy[0]:.0f}, {xyxy[3]-xyxy[1]:.0f})")
|
| 68 |
+
else:
|
| 69 |
+
print(" 객체가 탐지되지 않았습니다.")
|
| 70 |
+
|
| 71 |
+
# 시각화
|
| 72 |
+
if show:
|
| 73 |
+
for r in results:
|
| 74 |
+
img = r.plot() # BGR
|
| 75 |
+
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
| 76 |
+
|
| 77 |
+
plt.figure(figsize=(12, 8))
|
| 78 |
+
plt.imshow(img_rgb)
|
| 79 |
+
plt.axis('off')
|
| 80 |
+
plt.title(f"Detection Results (conf={conf})", fontsize=14)
|
| 81 |
+
plt.tight_layout()
|
| 82 |
+
plt.show()
|
| 83 |
+
|
| 84 |
+
print("\n✅ 예측 완료!")
|
| 85 |
+
if save:
|
| 86 |
+
print(f"결과 저장: runs/detect/predict/")
|
| 87 |
+
|
| 88 |
+
return results
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def predict_folder(model_path, folder_path, conf=0.25, save=True):
|
| 92 |
+
"""
|
| 93 |
+
폴더 내 모든 이미지 예측
|
| 94 |
+
|
| 95 |
+
Args:
|
| 96 |
+
model_path: 모델 경로
|
| 97 |
+
folder_path: 이미지 폴더 경로
|
| 98 |
+
conf: 신뢰도 임계값
|
| 99 |
+
save: 결과 저장 여부
|
| 100 |
+
"""
|
| 101 |
+
|
| 102 |
+
print("=" * 60)
|
| 103 |
+
print("폴더 예측")
|
| 104 |
+
print("=" * 60)
|
| 105 |
+
|
| 106 |
+
# 모델 로드
|
| 107 |
+
model = YOLO(model_path)
|
| 108 |
+
|
| 109 |
+
# 이미지 파일 찾기
|
| 110 |
+
folder = Path(folder_path)
|
| 111 |
+
image_files = list(folder.glob('*.[jJ][pP][gG]')) + \
|
| 112 |
+
list(folder.glob('*.[pP][nN][gG]'))
|
| 113 |
+
|
| 114 |
+
print(f"폴더: {folder_path}")
|
| 115 |
+
print(f"발견된 이미지: {len(image_files)}개")
|
| 116 |
+
|
| 117 |
+
if len(image_files) == 0:
|
| 118 |
+
print("❌ 이미지를 찾을 수 없습니다.")
|
| 119 |
+
return None
|
| 120 |
+
|
| 121 |
+
# 예측
|
| 122 |
+
results = model.predict(
|
| 123 |
+
source=folder_path,
|
| 124 |
+
save=save,
|
| 125 |
+
conf=conf,
|
| 126 |
+
iou=0.7,
|
| 127 |
+
show_labels=True,
|
| 128 |
+
show_conf=True,
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
# 통계
|
| 132 |
+
total_detections = sum(len(r.boxes) for r in results)
|
| 133 |
+
|
| 134 |
+
print(f"\n예측 완료!")
|
| 135 |
+
print(f" 처리한 이미지: {len(results)}개")
|
| 136 |
+
print(f" 총 탐지 객체: {total_detections}개")
|
| 137 |
+
print(f" 평균 객체/이미지: {total_detections/len(results):.2f}개")
|
| 138 |
+
|
| 139 |
+
if save:
|
| 140 |
+
print(f"\n결과 저장: runs/detect/predict/")
|
| 141 |
+
|
| 142 |
+
return results
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def compare_predictions(model_path, image_path, conf_levels=[0.1, 0.25, 0.5, 0.75]):
|
| 146 |
+
"""
|
| 147 |
+
다양한 신뢰도 임계값으로 예측 비교
|
| 148 |
+
|
| 149 |
+
Args:
|
| 150 |
+
model_path: 모델 경로
|
| 151 |
+
image_path: 이미지 경로
|
| 152 |
+
conf_levels: 신뢰도 임계값 리스트
|
| 153 |
+
"""
|
| 154 |
+
|
| 155 |
+
print("=" * 60)
|
| 156 |
+
print("신뢰도 임계값 비교")
|
| 157 |
+
print("=" * 60)
|
| 158 |
+
|
| 159 |
+
model = YOLO(model_path)
|
| 160 |
+
|
| 161 |
+
fig, axes = plt.subplots(2, 2, figsize=(16, 12))
|
| 162 |
+
axes = axes.flatten()
|
| 163 |
+
|
| 164 |
+
for i, conf in enumerate(conf_levels):
|
| 165 |
+
print(f"\n신뢰도 {conf:.2f} 예측 중...")
|
| 166 |
+
|
| 167 |
+
results = model.predict(
|
| 168 |
+
source=image_path,
|
| 169 |
+
conf=conf,
|
| 170 |
+
save=False,
|
| 171 |
+
verbose=False
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
for r in results:
|
| 175 |
+
img = r.plot()
|
| 176 |
+
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
|
| 177 |
+
|
| 178 |
+
axes[i].imshow(img_rgb)
|
| 179 |
+
axes[i].axis('off')
|
| 180 |
+
axes[i].set_title(f'Confidence = {conf} ({len(r.boxes)} objects)',
|
| 181 |
+
fontsize=12, fontweight='bold')
|
| 182 |
+
|
| 183 |
+
plt.tight_layout()
|
| 184 |
+
plt.savefig('confidence_comparison.png', dpi=150, bbox_inches='tight')
|
| 185 |
+
print("\n✅ 비교 결과 저장: confidence_comparison.png")
|
| 186 |
+
plt.show()
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
if __name__ == '__main__':
|
| 190 |
+
import sys
|
| 191 |
+
|
| 192 |
+
# 기본 모델 경로
|
| 193 |
+
default_model = 'waste_classification/yolov8n_5class/weights/best.pt'
|
| 194 |
+
|
| 195 |
+
print("=" * 60)
|
| 196 |
+
print("YOLO 추론 테스트")
|
| 197 |
+
print("=" * 60)
|
| 198 |
+
|
| 199 |
+
# 모델 경로
|
| 200 |
+
if len(sys.argv) > 1:
|
| 201 |
+
model_path = sys.argv[1]
|
| 202 |
+
else:
|
| 203 |
+
print(f"\n모델 경로 (엔터: {default_model}):")
|
| 204 |
+
user_input = input().strip()
|
| 205 |
+
model_path = user_input if user_input else default_model
|
| 206 |
+
|
| 207 |
+
if not Path(model_path).exists():
|
| 208 |
+
print(f"❌ 모델을 찾을 수 없습니다: {model_path}")
|
| 209 |
+
sys.exit(1)
|
| 210 |
+
|
| 211 |
+
# 이미지 경로
|
| 212 |
+
if len(sys.argv) > 2:
|
| 213 |
+
image_path = sys.argv[2]
|
| 214 |
+
else:
|
| 215 |
+
default_image = 'data/batch_1/000006.jpg'
|
| 216 |
+
print(f"이미지 경로 (엔터: {default_image}):")
|
| 217 |
+
user_input = input().strip()
|
| 218 |
+
image_path = user_input if user_input else default_image
|
| 219 |
+
|
| 220 |
+
if not Path(image_path).exists():
|
| 221 |
+
print(f"❌ 이미지를 찾을 수 없습니다: {image_path}")
|
| 222 |
+
sys.exit(1)
|
| 223 |
+
|
| 224 |
+
# 예측 실행
|
| 225 |
+
print("\n작업 선택:")
|
| 226 |
+
print(" 1. 단일 이미지 예측")
|
| 227 |
+
print(" 2. 폴더 예측")
|
| 228 |
+
print(" 3. 신뢰도 비교")
|
| 229 |
+
|
| 230 |
+
choice = input("선택 (1/2/3, 엔터: 1): ").strip() or '1'
|
| 231 |
+
|
| 232 |
+
if choice == '1':
|
| 233 |
+
predict_image(model_path, image_path, conf=0.25, save=True, show=True)
|
| 234 |
+
elif choice == '2':
|
| 235 |
+
folder = Path(image_path).parent if Path(image_path).is_file() else image_path
|
| 236 |
+
predict_folder(model_path, folder, conf=0.25, save=True)
|
| 237 |
+
elif choice == '3':
|
| 238 |
+
compare_predictions(model_path, image_path)
|
| 239 |
+
else:
|
| 240 |
+
print("잘못된 선택입니다.")
|
quick_train.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
빠른 테스트용 학습 스크립트 (5 에포크만)
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from ultralytics import YOLO
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
print("GPU 사용 가능:", torch.cuda.is_available())
|
| 9 |
+
|
| 10 |
+
# 모델 로드
|
| 11 |
+
model = YOLO('yolov8n.pt')
|
| 12 |
+
|
| 13 |
+
# 빠른 테스트 학습 (5 에포크만)
|
| 14 |
+
results = model.train(
|
| 15 |
+
data='dataset_split/data.yaml',
|
| 16 |
+
epochs=5,
|
| 17 |
+
imgsz=640,
|
| 18 |
+
batch=8,
|
| 19 |
+
device='0' if torch.cuda.is_available() else 'cpu',
|
| 20 |
+
project='test_run',
|
| 21 |
+
name='quick_test',
|
| 22 |
+
exist_ok=True,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
print("\n테스트 학습 완료!")
|
| 26 |
+
print("결과 확인: test_run/quick_test/")
|
requirements.txt
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# YOLO 학습을 위한 패키지
|
| 2 |
+
ultralytics>=8.0.0
|
| 3 |
+
torch>=2.0.0
|
| 4 |
+
torchvision>=0.15.0
|
| 5 |
+
opencv-python>=4.8.0
|
| 6 |
+
pillow>=10.0.0
|
| 7 |
+
pyyaml>=6.0
|
| 8 |
+
matplotlib>=3.7.0
|
| 9 |
+
seaborn>=0.12.0
|
| 10 |
+
pandas>=2.0.0
|
| 11 |
+
scipy>=1.10.0
|
| 12 |
+
tqdm>=4.65.0
|
| 13 |
+
scikit-learn>=1.3.0
|
| 14 |
+
|
| 15 |
+
# Optional: Weights & Biases (학습 로깅)
|
| 16 |
+
# wandb>=0.15.0
|
| 17 |
+
|
| 18 |
+
# Optional: TensorBoard (학습 모니터링)
|
| 19 |
+
# tensorboard>=2.13.0
|
split_train_val.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
데이터셋을 Train/Val로 8:2 분할하는 스크립트
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import shutil
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from sklearn.model_selection import train_test_split
|
| 9 |
+
from tqdm import tqdm
|
| 10 |
+
import random
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def split_dataset(
|
| 14 |
+
images_dir='data',
|
| 15 |
+
labels_dir='labels_5classes',
|
| 16 |
+
output_base='dataset_split',
|
| 17 |
+
train_ratio=0.8,
|
| 18 |
+
seed=42
|
| 19 |
+
):
|
| 20 |
+
"""
|
| 21 |
+
데이터셋을 train/val로 분할
|
| 22 |
+
|
| 23 |
+
Args:
|
| 24 |
+
images_dir: 원본 이미지 디렉토리
|
| 25 |
+
labels_dir: 원본 레이블 디렉토리
|
| 26 |
+
output_base: 출력 디렉토리 이름
|
| 27 |
+
train_ratio: 학습 데이터 비율
|
| 28 |
+
seed: 랜덤 시드
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
random.seed(seed)
|
| 32 |
+
|
| 33 |
+
print("=" * 60)
|
| 34 |
+
print("데이터셋 Train/Val 분할")
|
| 35 |
+
print("=" * 60)
|
| 36 |
+
|
| 37 |
+
images_path = Path(images_dir)
|
| 38 |
+
labels_path = Path(labels_dir)
|
| 39 |
+
output_path = Path(output_base)
|
| 40 |
+
|
| 41 |
+
# 모든 이미지 파일 찾기
|
| 42 |
+
all_images = []
|
| 43 |
+
for batch_dir in sorted(images_path.glob('batch_*')):
|
| 44 |
+
for img_file in batch_dir.glob('*.[jJ][pP][gG]'):
|
| 45 |
+
# 상대 경로 저장 (batch_1/000006.jpg)
|
| 46 |
+
rel_path = img_file.relative_to(images_path)
|
| 47 |
+
all_images.append(str(rel_path))
|
| 48 |
+
|
| 49 |
+
print(f"총 이미지 수: {len(all_images)}")
|
| 50 |
+
|
| 51 |
+
# Train/Val 분할
|
| 52 |
+
train_images, val_images = train_test_split(
|
| 53 |
+
all_images,
|
| 54 |
+
train_size=train_ratio,
|
| 55 |
+
random_state=seed,
|
| 56 |
+
shuffle=True
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
print(f"Train 이미지: {len(train_images)} ({len(train_images)/len(all_images)*100:.1f}%)")
|
| 60 |
+
print(f"Val 이미지: {len(val_images)} ({len(val_images)/len(all_images)*100:.1f}%)")
|
| 61 |
+
|
| 62 |
+
# 출력 디렉토리 생성
|
| 63 |
+
train_images_dir = output_path / 'images' / 'train'
|
| 64 |
+
train_labels_dir = output_path / 'labels' / 'train'
|
| 65 |
+
val_images_dir = output_path / 'images' / 'val'
|
| 66 |
+
val_labels_dir = output_path / 'labels' / 'val'
|
| 67 |
+
|
| 68 |
+
for dir_path in [train_images_dir, train_labels_dir, val_images_dir, val_labels_dir]:
|
| 69 |
+
dir_path.mkdir(parents=True, exist_ok=True)
|
| 70 |
+
|
| 71 |
+
# 배치 폴더 생성
|
| 72 |
+
for batch_num in range(1, 16):
|
| 73 |
+
(train_images_dir / f'batch_{batch_num}').mkdir(exist_ok=True)
|
| 74 |
+
(train_labels_dir / f'batch_{batch_num}').mkdir(exist_ok=True)
|
| 75 |
+
(val_images_dir / f'batch_{batch_num}').mkdir(exist_ok=True)
|
| 76 |
+
(val_labels_dir / f'batch_{batch_num}').mkdir(exist_ok=True)
|
| 77 |
+
|
| 78 |
+
# Train 데이터 복사
|
| 79 |
+
print("\nTrain 데이터 복사 중...")
|
| 80 |
+
for img_rel_path in tqdm(train_images, desc="Train"):
|
| 81 |
+
# 이미지 복사
|
| 82 |
+
src_img = images_path / img_rel_path
|
| 83 |
+
dst_img = train_images_dir / img_rel_path
|
| 84 |
+
shutil.copy2(src_img, dst_img)
|
| 85 |
+
|
| 86 |
+
# 레이블 복사
|
| 87 |
+
label_rel_path = img_rel_path.replace('.jpg', '.txt').replace('.JPG', '.txt')
|
| 88 |
+
src_label = labels_path / label_rel_path
|
| 89 |
+
dst_label = train_labels_dir / label_rel_path
|
| 90 |
+
|
| 91 |
+
if src_label.exists():
|
| 92 |
+
shutil.copy2(src_label, dst_label)
|
| 93 |
+
|
| 94 |
+
# Val 데이터 복사
|
| 95 |
+
print("Val 데이터 복사 중...")
|
| 96 |
+
for img_rel_path in tqdm(val_images, desc="Val"):
|
| 97 |
+
# 이미지 복사
|
| 98 |
+
src_img = images_path / img_rel_path
|
| 99 |
+
dst_img = val_images_dir / img_rel_path
|
| 100 |
+
shutil.copy2(src_img, dst_img)
|
| 101 |
+
|
| 102 |
+
# 레이블 복사
|
| 103 |
+
label_rel_path = img_rel_path.replace('.jpg', '.txt').replace('.JPG', '.txt')
|
| 104 |
+
src_label = labels_path / label_rel_path
|
| 105 |
+
dst_label = val_labels_dir / label_rel_path
|
| 106 |
+
|
| 107 |
+
if src_label.exists():
|
| 108 |
+
shutil.copy2(src_label, dst_label)
|
| 109 |
+
|
| 110 |
+
# train.txt, val.txt 생성 (이미지 경로 리스트)
|
| 111 |
+
print("\n이미지 리스트 파일 생성 중...")
|
| 112 |
+
|
| 113 |
+
with open(output_path / 'train.txt', 'w') as f:
|
| 114 |
+
for img_path in train_images:
|
| 115 |
+
abs_path = (output_path / 'images' / 'train' / img_path).absolute()
|
| 116 |
+
f.write(f"{abs_path}\n")
|
| 117 |
+
|
| 118 |
+
with open(output_path / 'val.txt', 'w') as f:
|
| 119 |
+
for img_path in val_images:
|
| 120 |
+
abs_path = (output_path / 'images' / 'val' / img_path).absolute()
|
| 121 |
+
f.write(f"{abs_path}\n")
|
| 122 |
+
|
| 123 |
+
# data.yaml 생성
|
| 124 |
+
print("data.yaml 생성 중...")
|
| 125 |
+
|
| 126 |
+
yaml_content = f"""# YOLO Dataset Configuration
|
| 127 |
+
# Train/Val Split: {train_ratio*100:.0f}/{(1-train_ratio)*100:.0f}
|
| 128 |
+
|
| 129 |
+
path: {output_path.absolute()}
|
| 130 |
+
train: images/train
|
| 131 |
+
val: images/val
|
| 132 |
+
|
| 133 |
+
# Classes
|
| 134 |
+
nc: 5
|
| 135 |
+
names:
|
| 136 |
+
0: Plastic
|
| 137 |
+
1: Vinyl
|
| 138 |
+
2: Can
|
| 139 |
+
3: Glass
|
| 140 |
+
4: Paper
|
| 141 |
+
"""
|
| 142 |
+
|
| 143 |
+
with open(output_path / 'data.yaml', 'w', encoding='utf-8') as f:
|
| 144 |
+
f.write(yaml_content)
|
| 145 |
+
|
| 146 |
+
# 통계 출력
|
| 147 |
+
print("\n" + "=" * 60)
|
| 148 |
+
print("분할 완료!")
|
| 149 |
+
print("=" * 60)
|
| 150 |
+
print(f"출력 디렉토리: {output_path.absolute()}")
|
| 151 |
+
print(f"\n디렉토리 구조:")
|
| 152 |
+
print(f"{output_base}/")
|
| 153 |
+
print(f"├── images/")
|
| 154 |
+
print(f"│ ├── train/ ({len(train_images)} images)")
|
| 155 |
+
print(f"│ └── val/ ({len(val_images)} images)")
|
| 156 |
+
print(f"├── labels/")
|
| 157 |
+
print(f"│ ├── train/ ({len(train_images)} labels)")
|
| 158 |
+
print(f"│ └── val/ ({len(val_images)} labels)")
|
| 159 |
+
print(f"├── data.yaml")
|
| 160 |
+
print(f"├── train.txt")
|
| 161 |
+
print(f"└── val.txt")
|
| 162 |
+
|
| 163 |
+
# 클래스별 분포 확인
|
| 164 |
+
print(f"\n클래스별 분포 (Train):")
|
| 165 |
+
check_class_distribution(train_labels_dir)
|
| 166 |
+
|
| 167 |
+
print(f"\n클래스별 분포 (Val):")
|
| 168 |
+
check_class_distribution(val_labels_dir)
|
| 169 |
+
|
| 170 |
+
return output_path
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def check_class_distribution(labels_dir):
|
| 174 |
+
"""레이블 디렉토리에서 클래스 분포 확인"""
|
| 175 |
+
class_names = ['Plastic', 'Vinyl', 'Can', 'Glass', 'Paper']
|
| 176 |
+
class_counts = {i: 0 for i in range(5)}
|
| 177 |
+
|
| 178 |
+
labels_path = Path(labels_dir)
|
| 179 |
+
|
| 180 |
+
for label_file in labels_path.glob('**/*.txt'):
|
| 181 |
+
with open(label_file, 'r') as f:
|
| 182 |
+
for line in f:
|
| 183 |
+
parts = line.strip().split()
|
| 184 |
+
if len(parts) >= 5:
|
| 185 |
+
class_id = int(parts[0])
|
| 186 |
+
class_counts[class_id] += 1
|
| 187 |
+
|
| 188 |
+
total = sum(class_counts.values())
|
| 189 |
+
|
| 190 |
+
for class_id, count in class_counts.items():
|
| 191 |
+
percentage = (count / total * 100) if total > 0 else 0
|
| 192 |
+
print(f" {class_id} ({class_names[class_id]:>8s}): {count:4d} ({percentage:5.2f}%)")
|
| 193 |
+
|
| 194 |
+
print(f" {'Total':>11s}: {total:4d}")
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
if __name__ == '__main__':
|
| 198 |
+
import sys
|
| 199 |
+
|
| 200 |
+
# scikit-learn 확인
|
| 201 |
+
try:
|
| 202 |
+
from sklearn.model_selection import train_test_split
|
| 203 |
+
except ImportError:
|
| 204 |
+
print("❌ scikit-learn이 설치되어 있지 않습니다.")
|
| 205 |
+
print("설치: pip install scikit-learn")
|
| 206 |
+
sys.exit(1)
|
| 207 |
+
|
| 208 |
+
print("\n데이터셋을 Train/Val로 분할합니다.")
|
| 209 |
+
print("비율: Train 80% / Val 20%")
|
| 210 |
+
|
| 211 |
+
response = input("\n계속하시겠습니까? (y/n): ")
|
| 212 |
+
if response.lower() != 'y':
|
| 213 |
+
print("취소되었습니다.")
|
| 214 |
+
sys.exit(0)
|
| 215 |
+
|
| 216 |
+
# 분할 실행
|
| 217 |
+
output_dir = split_dataset(
|
| 218 |
+
images_dir='data',
|
| 219 |
+
labels_dir='labels_5classes',
|
| 220 |
+
output_base='dataset_split',
|
| 221 |
+
train_ratio=0.8,
|
| 222 |
+
seed=42
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
print("\n✅ 완료! 이제 다음 명령으로 학습하세요:")
|
| 226 |
+
print(f" python train_yolo.py")
|
train_yolo.py
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
YOLO 쓰레기 분류 모델 학습 스크립트
|
| 3 |
+
|
| 4 |
+
5개 클래스: 플라스틱, 비닐, 캔, 유리, 종이
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from ultralytics import YOLO
|
| 8 |
+
import torch
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def check_environment():
|
| 13 |
+
"""학습 환경 확인"""
|
| 14 |
+
print("=" * 60)
|
| 15 |
+
print("학습 환경 확인")
|
| 16 |
+
print("=" * 60)
|
| 17 |
+
|
| 18 |
+
# CUDA 사용 가능 여부
|
| 19 |
+
cuda_available = torch.cuda.is_available()
|
| 20 |
+
print(f"CUDA 사용 가능: {cuda_available}")
|
| 21 |
+
|
| 22 |
+
if cuda_available:
|
| 23 |
+
print(f"GPU 이름: {torch.cuda.get_device_name(0)}")
|
| 24 |
+
print(f"GPU 메모리: {torch.cuda.get_device_properties(0).total_memory / 1024**3:.2f} GB")
|
| 25 |
+
else:
|
| 26 |
+
print("⚠️ GPU를 사용할 수 없습니다. CPU로 학습하면 매우 느립니다.")
|
| 27 |
+
|
| 28 |
+
# 데이터 경로 확인
|
| 29 |
+
data_yaml = Path('dataset_split/data.yaml')
|
| 30 |
+
if data_yaml.exists():
|
| 31 |
+
print(f"✅ 데이터 설정 파일 존재: {data_yaml}")
|
| 32 |
+
else:
|
| 33 |
+
print(f"❌ 데이터 설정 파일 없음: {data_yaml}")
|
| 34 |
+
print(f"먼저 'python split_train_val.py'를 실행하세요.")
|
| 35 |
+
return False
|
| 36 |
+
|
| 37 |
+
print("=" * 60)
|
| 38 |
+
return True
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def train_model(
|
| 42 |
+
model_size='n', # n(nano), s(small), m(medium), l(large), x(xlarge)
|
| 43 |
+
epochs=100,
|
| 44 |
+
batch_size=16,
|
| 45 |
+
img_size=640,
|
| 46 |
+
device='0', # '0' for GPU, 'cpu' for CPU
|
| 47 |
+
patience=50, # Early stopping patience
|
| 48 |
+
project_name='waste_classification'
|
| 49 |
+
):
|
| 50 |
+
"""
|
| 51 |
+
YOLO 모델 학습
|
| 52 |
+
|
| 53 |
+
Args:
|
| 54 |
+
model_size: 모델 크기 (n/s/m/l/x)
|
| 55 |
+
- n (nano): 가장 빠름, 정확도 낮음 (3.2M params)
|
| 56 |
+
- s (small): 빠름 (11.2M params)
|
| 57 |
+
- m (medium): 균형 (25.9M params)
|
| 58 |
+
- l (large): 느림, 정확도 높음 (43.7M params)
|
| 59 |
+
- x (xlarge): 가장 느림, 정확도 최고 (68.2M params)
|
| 60 |
+
epochs: 학습 에포크 수
|
| 61 |
+
batch_size: 배치 크기 (GPU 메모리에 따라 조정)
|
| 62 |
+
img_size: 이미지 크기
|
| 63 |
+
device: 'cuda' 또는 'cpu'
|
| 64 |
+
patience: Early stopping 기다림 에포크
|
| 65 |
+
project_name: 프로젝트 이름
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
print("\n" + "=" * 60)
|
| 69 |
+
print(f"YOLO v8 {model_size.upper()} 모델 학습 시작")
|
| 70 |
+
print("=" * 60)
|
| 71 |
+
|
| 72 |
+
# 모델 로드
|
| 73 |
+
model = YOLO(f'yolov8{model_size}.pt')
|
| 74 |
+
|
| 75 |
+
# 학습 파라미터 출력
|
| 76 |
+
print(f"\n학습 설정:")
|
| 77 |
+
print(f" - 모델: YOLOv8{model_size}")
|
| 78 |
+
print(f" - 에포크: {epochs}")
|
| 79 |
+
print(f" - 배치 크기: {batch_size}")
|
| 80 |
+
print(f" - 이미지 크기: {img_size}")
|
| 81 |
+
print(f" - 디바이스: {device}")
|
| 82 |
+
print(f" - Early Stopping Patience: {patience}")
|
| 83 |
+
print()
|
| 84 |
+
|
| 85 |
+
# 학습 실행
|
| 86 |
+
results = model.train(
|
| 87 |
+
data='dataset_split/data.yaml',
|
| 88 |
+
epochs=epochs,
|
| 89 |
+
imgsz=img_size,
|
| 90 |
+
batch=batch_size,
|
| 91 |
+
device=device,
|
| 92 |
+
patience=patience,
|
| 93 |
+
save=True,
|
| 94 |
+
save_period=10, # 10 에포크마다 체크포인트 저장
|
| 95 |
+
project=project_name,
|
| 96 |
+
name=f'yolov8{model_size}_5class',
|
| 97 |
+
exist_ok=True,
|
| 98 |
+
pretrained=True,
|
| 99 |
+
optimizer='auto',
|
| 100 |
+
verbose=True,
|
| 101 |
+
seed=42,
|
| 102 |
+
deterministic=True,
|
| 103 |
+
single_cls=False,
|
| 104 |
+
rect=False,
|
| 105 |
+
cos_lr=False,
|
| 106 |
+
close_mosaic=10,
|
| 107 |
+
resume=False,
|
| 108 |
+
amp=True, # Automatic Mixed Precision
|
| 109 |
+
fraction=1.0,
|
| 110 |
+
profile=False,
|
| 111 |
+
overlap_mask=True,
|
| 112 |
+
mask_ratio=4,
|
| 113 |
+
dropout=0.0,
|
| 114 |
+
val=True,
|
| 115 |
+
plots=True,
|
| 116 |
+
|
| 117 |
+
# Augmentation
|
| 118 |
+
hsv_h=0.015,
|
| 119 |
+
hsv_s=0.7,
|
| 120 |
+
hsv_v=0.4,
|
| 121 |
+
degrees=0.0,
|
| 122 |
+
translate=0.1,
|
| 123 |
+
scale=0.5,
|
| 124 |
+
shear=0.0,
|
| 125 |
+
perspective=0.0,
|
| 126 |
+
flipud=0.0,
|
| 127 |
+
fliplr=0.5,
|
| 128 |
+
mosaic=1.0,
|
| 129 |
+
mixup=0.0,
|
| 130 |
+
copy_paste=0.0,
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
print("\n" + "=" * 60)
|
| 134 |
+
print("학습 완료!")
|
| 135 |
+
print("=" * 60)
|
| 136 |
+
|
| 137 |
+
return model, results
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def validate_model(model, project_name='waste_classification', model_size='n'):
|
| 141 |
+
"""학습된 모델 검증"""
|
| 142 |
+
print("\n" + "=" * 60)
|
| 143 |
+
print("모델 검증 중...")
|
| 144 |
+
print("=" * 60)
|
| 145 |
+
|
| 146 |
+
# 검증 실행
|
| 147 |
+
metrics = model.val()
|
| 148 |
+
|
| 149 |
+
print(f"\n검증 결과:")
|
| 150 |
+
print(f" - mAP50: {metrics.box.map50:.4f}")
|
| 151 |
+
print(f" - mAP50-95: {metrics.box.map:.4f}")
|
| 152 |
+
print(f" - Precision: {metrics.box.mp:.4f}")
|
| 153 |
+
print(f" - Recall: {metrics.box.mr:.4f}")
|
| 154 |
+
|
| 155 |
+
return metrics
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def test_inference(model, test_image_path='data/batch_1/000006.jpg'):
|
| 159 |
+
"""테스트 이미지로 추론"""
|
| 160 |
+
print("\n" + "=" * 60)
|
| 161 |
+
print("추론 테스트")
|
| 162 |
+
print("=" * 60)
|
| 163 |
+
|
| 164 |
+
# 추론 실행
|
| 165 |
+
results = model.predict(
|
| 166 |
+
source=test_image_path,
|
| 167 |
+
save=True,
|
| 168 |
+
conf=0.25,
|
| 169 |
+
iou=0.7,
|
| 170 |
+
show_labels=True,
|
| 171 |
+
show_conf=True,
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
# 결과 출력
|
| 175 |
+
for r in results:
|
| 176 |
+
print(f"\n이미지: {test_image_path}")
|
| 177 |
+
print(f"탐지된 객체 수: {len(r.boxes)}")
|
| 178 |
+
for box in r.boxes:
|
| 179 |
+
cls_id = int(box.cls[0])
|
| 180 |
+
conf = float(box.conf[0])
|
| 181 |
+
cls_name = r.names[cls_id]
|
| 182 |
+
print(f" - {cls_name}: {conf:.2f}")
|
| 183 |
+
|
| 184 |
+
return results
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
if __name__ == '__main__':
|
| 188 |
+
# 환경 확인
|
| 189 |
+
if not check_environment():
|
| 190 |
+
print("환경 설정을 확인해주세요.")
|
| 191 |
+
exit(1)
|
| 192 |
+
|
| 193 |
+
# GPU 사용 가능 여부에 따라 디바이스 설정
|
| 194 |
+
device = '0' if torch.cuda.is_available() else 'cpu'
|
| 195 |
+
|
| 196 |
+
# 학습 설정
|
| 197 |
+
MODEL_SIZE = 'n' # nano 모델 (빠른 학습)
|
| 198 |
+
EPOCHS = 100
|
| 199 |
+
BATCH_SIZE = 16 if torch.cuda.is_available() else 4
|
| 200 |
+
IMG_SIZE = 640
|
| 201 |
+
|
| 202 |
+
print(f"\n사용할 설정:")
|
| 203 |
+
print(f" 모델: yolov8{MODEL_SIZE}")
|
| 204 |
+
print(f" 에포크: {EPOCHS}")
|
| 205 |
+
print(f" 배치: {BATCH_SIZE}")
|
| 206 |
+
print(f" 디바이스: {'GPU' if device == '0' else 'CPU'}")
|
| 207 |
+
|
| 208 |
+
# 사용자 확인
|
| 209 |
+
response = input("\n학습을 시작하시겠습니까? (y/n): ")
|
| 210 |
+
if response.lower() != 'y':
|
| 211 |
+
print("학습이 취소되었습니다.")
|
| 212 |
+
exit(0)
|
| 213 |
+
|
| 214 |
+
# 모델 학습
|
| 215 |
+
model, results = train_model(
|
| 216 |
+
model_size=MODEL_SIZE,
|
| 217 |
+
epochs=EPOCHS,
|
| 218 |
+
batch_size=BATCH_SIZE,
|
| 219 |
+
img_size=IMG_SIZE,
|
| 220 |
+
device=device,
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
# 모델 검증
|
| 224 |
+
metrics = validate_model(model, model_size=MODEL_SIZE)
|
| 225 |
+
|
| 226 |
+
# 추론 테스트
|
| 227 |
+
test_inference(model)
|
| 228 |
+
|
| 229 |
+
print("\n" + "=" * 60)
|
| 230 |
+
print("모든 작업 완료!")
|
| 231 |
+
print("=" * 60)
|
| 232 |
+
print(f"\n학습된 모델 위치: waste_classification/yolov8{MODEL_SIZE}_5class/weights/best.pt")
|
| 233 |
+
print(f"학습 결과 그래프: waste_classification/yolov8{MODEL_SIZE}_5class/")
|