
강의 영상 보기 (새 탭에서 재생)YouTube
📓Google Colab에서 실습하기
이 레슨은 PyTorch/GPU가 필요합니다. 노트북을 다운로드 후 Google Colab에서 열어주세요.
학습 내용
데이터 증강
학습 목표
이 레슨을 완료하면:
- •데이터 증강의 필요성과 효과를 이해합니다
- •다양한 이미지 증강 기법을 적용합니다
- •torchvision.transforms를 능숙하게 사용합니다
- •데이터 증강이 모델 성능에 미치는 영향을 파악합니다
핵심 메시지
"같은 이미지를 다르게 보는 연습" 사람은 고양이 사진을 뒤집어도, 회전해도, 밝기가 달라도 고양이로 인식합니다. 데이터 증강은 모델에게 이런 "불변성"을 가르치는 방법입니다.
1. 왜 데이터 증강이 필요한가?
데이터 부족의 문제
| 문제 | 원인 | 결과 |
|---|---|---|
| 과적합 | 훈련 데이터 암기 | 새 데이터에서 성능 하락 |
| 다양성 부족 | 한정된 조건의 데이터 | 실제 환경에서 실패 |
| 수집 비용 | 라벨링 비용 높음 | 충분한 데이터 확보 어려움 |
데이터 증강의 효과
| 효과 | 설명 |
|---|---|
| 데이터 양 증가 | 가상으로 훈련 데이터 확장 |
| 과적합 방지 | 매번 다른 변형 이미지 학습 |
| 불변성 학습 | 회전, 이동, 색상 변화에 강건 |
| 일반화 향상 | 실제 환경에서 성능 개선 |
2. 주요 증강 기법
기하학적 변환
| 기법 | 설명 | PyTorch |
|---|---|---|
| 좌우 반전 | 50% 확률로 뒤집기 | RandomHorizontalFlip() |
| 상하 반전 | 50% 확률로 뒤집기 | RandomVerticalFlip() |
| 회전 | 임의 각도 회전 | RandomRotation(degrees) |
| 크롭 | 일부분 자르기 | RandomCrop(size, padding) |
| 크기 조절 | 랜덤 크기 변경 후 자르기 | RandomResizedCrop(size) |
색상 변환
| 기법 | 설명 | PyTorch |
|---|---|---|
| 밝기 | 밝기 조절 | ColorJitter(brightness) |
| 대비 | 대비 조절 | ColorJitter(contrast) |
| 채도 | 색상 강도 조절 | ColorJitter(saturation) |
| 색조 | 색상 변경 | ColorJitter(hue) |
| 흑백 | 그레이스케일 변환 | RandomGrayscale(p) |
3. PyTorch 구현
🔬 실습: 증강 기법 시각화
python⚠️ 로컬 실행 필요import torch from torchvision import transforms from PIL import Image import matplotlib.pyplot as plt import numpy as np # ═══════════════════════════════════════════════════════════════ # 📊 데이터 증강 기법 시각화 # ═══════════════════════════════════════════════════════════════ # 샘플 이미지 생성 (체커보드 패턴) def create_sample_image(): img = np.zeros((64, 64, 3), dtype=np.uint8) img[::8, ::8] = [255, 100, 100] # 빨간 점 img[4::8, 4::8] = [100, 100, 255] # 파란 점 for i in range(64): for j in range(64): if (i // 8 + j // 8) % 2 == 0: img[i, j] = [200, 200, 200] return Image.fromarray(img) original = create_sample_image() # 다양한 증강 기법 augmentations = { 'Original': transforms.Compose([transforms.ToTensor()]), 'H-Flip': transforms.Compose([ transforms.RandomHorizontalFlip(p=1.0), transforms.ToTensor() ]), 'Rotation (45)': transforms.Compose([ transforms.RandomRotation([45, 45]), transforms.ToTensor() ]), 'Random Crop': transforms.Compose([ transforms.RandomCrop(48), transforms.Resize(64), transforms.ToTensor() ]), 'Color Jitter': transforms.Compose([ transforms.ColorJitter(brightness=0.5, contrast=0.5, saturation=0.5), transforms.ToTensor() ]), 'Combined': transforms.Compose([ transforms.RandomHorizontalFlip(), transforms.RandomRotation(15), transforms.ColorJitter(0.2, 0.2, 0.2), transforms.ToTensor() ]), } # 시각화 fig, axes = plt.subplots(2, 3, figsize=(12, 8)) for ax, (name, transform) in zip(axes.flat, augmentations.items()): img_tensor = transform(original) img_np = img_tensor.permute(1, 2, 0).numpy() img_np = np.clip(img_np, 0, 1) ax.imshow(img_np) ax.set_title(name, fontsize=12) ax.axis('off') plt.suptitle('Data Augmentation Techniques', fontsize=14, fontweight='bold') plt.tight_layout() plt.show()
4. 실전 증강 파이프라인
🔬 실습: CIFAR-10 증강 파이프라인
pythonfrom torchvision import transforms # ═══════════════════════════════════════════════════════════════ # 📊 실전 데이터 증강 파이프라인 # ═══════════════════════════════════════════════════════════════ # 훈련용 (강한 증강) train_transform = transforms.Compose([ # 기하학적 변환 transforms.RandomHorizontalFlip(p=0.5), transforms.RandomRotation(15), transforms.RandomCrop(32, padding=4), # 색상 변환 transforms.ColorJitter( brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1 ), # 텐서 변환 및 정규화 transforms.ToTensor(), transforms.Normalize( mean=[0.4914, 0.4822, 0.4465], std=[0.2470, 0.2435, 0.2616] ), # 추가 정규화 (선택) transforms.RandomErasing(p=0.2), # 일부 영역 지우기 ]) # 테스트용 (증강 없음) test_transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize( mean=[0.4914, 0.4822, 0.4465], std=[0.2470, 0.2435, 0.2616] ), ]) print("=" * 50) print("📊 훈련용 증강 파이프라인") print("=" * 50) print("1. RandomHorizontalFlip (p=0.5)") print("2. RandomRotation (±15°)") print("3. RandomCrop (32, padding=4)") print("4. ColorJitter (밝기, 대비, 채도, 색조)") print("5. ToTensor + Normalize") print("6. RandomErasing (p=0.2)") print("\n📊 테스트용 파이프라인") print("=" * 50) print("1. ToTensor + Normalize (증강 없음)")
5. 증강 효과 검증
🔬 실습: 증강 유무에 따른 성능 비교
python⚠️ 로컬 실행 필요import torch import torch.nn as nn import matplotlib.pyplot as plt # ═══════════════════════════════════════════════════════════════ # 📊 데이터 증강 효과 시뮬레이션 # ═══════════════════════════════════════════════════════════════ # 시뮬레이션 데이터 (실제 학습 결과 시뮬레이션) epochs = list(range(1, 31)) # 증강 없이 학습 no_aug_train = [90 - 30*np.exp(-e/5) + np.random.randn()*2 for e in epochs] no_aug_test = [75 - 20*np.exp(-e/8) + np.random.randn()*2 for e in epochs] # 증강과 함께 학습 with_aug_train = [85 - 25*np.exp(-e/7) + np.random.randn()*2 for e in epochs] with_aug_test = [82 - 15*np.exp(-e/10) + np.random.randn()*2 for e in epochs] fig, axes = plt.subplots(1, 2, figsize=(14, 5)) # 훈련 정확도 axes[0].plot(epochs, no_aug_train, 'b-', label='No Augmentation', linewidth=2) axes[0].plot(epochs, with_aug_train, 'g-', label='With Augmentation', linewidth=2) axes[0].set_xlabel('Epoch') axes[0].set_ylabel('Train Accuracy (%)') axes[0].set_title('Train Accuracy') axes[0].legend() axes[0].grid(True, alpha=0.3) axes[0].set_ylim(50, 95) # 테스트 정확도 axes[1].plot(epochs, no_aug_test, 'b-', label='No Augmentation', linewidth=2) axes[1].plot(epochs, with_aug_test, 'g-', label='With Augmentation', linewidth=2) axes[1].axhline(y=80, color='r', linestyle='--', alpha=0.5, label='Target Accuracy') axes[1].set_xlabel('Epoch') axes[1].set_ylabel('Test Accuracy (%)') axes[1].set_title('Test Accuracy') axes[1].legend() axes[1].grid(True, alpha=0.3) axes[1].set_ylim(50, 95) plt.suptitle('Data Augmentation Effect Comparison', fontsize=14, fontweight='bold') plt.tight_layout() plt.show() print("=" * 55) print("📊 결과 분석") print("=" * 55) print("증강 없음:") print(" - 훈련 정확도 높음, 테스트 정확도 낮음 → 과적합!") print("\n증강 있음:") print(" - 훈련 정확도 약간 낮음, 테스트 정확도 높음 → 일반화 성공!") print("\n💡 데이터 증강은 과적합을 방지하고 일반화 성능을 높입니다!")
핵심 요약
| 증강 유형 | 기법 | 효과 |
|---|---|---|
| 기하학적 | Flip, Rotation, Crop | 위치/방향 불변성 |
| 색상 | ColorJitter, Grayscale | 조명/색상 불변성 |
| 삭제 | RandomErasing | 부분 가림에 강건 |
| 혼합 | Mixup, CutMix | 고급 정규화 |
학습 체크리스트
- • 데이터 증강의 필요성을 설명할 수 있다
- • 기하학적/색상 증강 기법을 구분한다
- • transforms.Compose로 파이프라인을 만들 수 있다
- • 훈련/테스트 시 증강 적용 차이를 안다
Level 5 완료!
축하합니다! CNN과 이미지 처리의 핵심을 모두 학습했습니다. 다음 Level에서는 순환 신경망(RNN)과 시퀀스 데이터 처리를 배웁니다!
레슨 정보
- 레벨
- Level 5: CNN & 이미지 처리
- 예상 소요 시간
- 40분
- 참고 영상
- YouTube 링크
💡실습 환경 안내
이 레벨은 PyTorch/GPU가 필요하여 Google Colab 사용을 권장합니다.
Colab은 무료 GPU를 제공하여 PyTorch, CNN, Transformer 등을 실행할 수 있습니다.