Skip to content

UpstageAILab5/upstageailab-cv-classification-cv_c1-pub

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

59 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

[Computer Vision] Document Type Classification

Table of Contents

I. Overview

  • Task Description
  • Data Structure
  • Evaluation Metric

II. Getting Started

  • Server Setup
  • Environment Setup
  • Basic Usage

III. Project Structure

  • Directory Structure
  • Experiment Management
  • Logging System

IV. Data Pipeline

  • Data Processing
  • Augmentation Strategies
  • Class Imbalance Handling
  • Validation Strategies

V. Model Development

  • Supported Architectures
  • Model Configuration
  • Training Process

VI. Advanced Features

  • Performance Optimization
  • Mixed Precision Training
  • Early Stopping
  • Label Smoothing
  • Domain Adaptation

VII. Development Guide

  • Git Convention
  • Troubleshooting
  • Examples

I. Overview

Task Description

Category Type
Task Type Recognition > Classification > Multi-class
Data Type Unstructured > Image
Evaluation Metric Macro F1 Score

: 주어진 Image Document 데이터를 17종 문서 타입으로 분류하는 Multi-class Classification

Data Structure

📂 Train Data

  • 이미지 수: 1570장
  • 클래스: 17종 (각 클래스당 46~100장)

구성:

  • train.csv: 이미지 ID와 클래스(Target) 매핑
  • train/: 실제 학습 이미지 폴더

📂 Test Data

  • 이미지 수: 3140장 (Train보다 많음)
  • 특징: Augmentation을 통해 현실 세계의 노이즈가 추가됨

Evaluation Metric

  • F1 Score: Precision과 Recall의 조화 평균
    • Macro F1 Score: 각 클래스별 F1 Score를 평균하여 계산
    • Micro F1 Score: 모든 클래스의 Precision과 Recall을 합산하여 계산

II. Getting Started

1. Server Setup (Optional)

chmod +x setup_server.sh
bash setup_server.sh
source ~/.bashrc

2. Environment Setup

# 1. Repository Clone
git clone https://github.com/kafkapple/upstageailab-cv-classification-cv_c1
cd upstageailab-cv-classification-cv_c1

# 2. Environment Setup
conda env create -f environment.yml

3. Basic Usage

# Training with default config (config_test.yaml)
python train.py

# Data analysis (default: test dataset)
python eda.py

III. Project Structure

1. Directory Structure

📦 project_root
├── 📜 train.py            # 학습 실행 스크립트
├── 📜 eda.py             # 데이터 분석 스크립트
├── 📜 setup_server.sh    # 서버 환경 설정
├── 📜 environment.yml    # 환경 설정 파일
├── 📂 configs/
│   ├── 📜 config.yaml    # 메인 설정 파일
├── 📂 examples/
│   ├── 📜 baseline.ipynb # 기본 학습 예제 노트북
├── 📂 src/
│   ├── 📜 __init__.py
│   ├── 📜 data.py       # 데이터셋 및 전처리
│   ├── 📜 models.py     # 모델 아키텍처
│   ├── 📜 trainer.py    # 학습 관리
│   ├── 📜 evaluator.py  # 성능 평가 및 시각화
│   ├── 📜 logger.py     # W&B 로깅
│   ├── 📜 visualizer.py # 데이터 시각화
│   └── 📜 utils.py      # 유틸리티 함수
└── 📂 outputs/          # 실험 결과물
    ├── 📂 {timestamp}/  # 각 실험별 고유 폴더
    │   ├── checkpoints/ # 모델 체크포인트
    │   ├── metrics/     # 성능 평가 결과
    │   ├── logs/        # 실험 로그결과
    │   └── reports/     # 학습 관련 리포트
    └── 📂 reports/      # EDA 결과물
        └── embedding/        # 임베딩 분석 결과 (default: test dataset)

2. Experiment Management

2.1 실험 결과 구조

outputs/
├── {timestamp}/           # 각 실험별 고유 폴더
│   ├── checkpoints/      # 모델 체크포인트
│   │   └── best.pt      # 최고 성능 모델
│   ├── metrics/         # 성능 평가 결과
│   │   ├── classification_report_{phase}.txt
│   │   ├── class_metrics_{phase}.png
│   │   ├── confusion_matrix_{phase}.png
│   │   └── learning_curves.png
│   ├── logs/           # 실험 로그
│   │   └── experiment.json  # 실험 설정 및 성능 지표
│   ├── predictions.csv  # test data 셋에 대한 예측 결과
│   └── reports/        # 학습 과정 리포트
│       └── augmentation/  # 데이터 증강 시각화
└── reports/              # EDA 결과물
    └── embedding/        # 임베딩 분석 결과 (default: test dataset)

3. Logging System

3.1 Weights & Biases Integration

logger:
  use_wandb: true
  entity: "ailab_upstage_fastcampus"
  project_name: "cv_test"  # 기본값
  metrics:
    epoch: ["loss", "accuracy", "f1", "precision", "recall"]
    class_metrics: ["f1", "precision", "recall"]

3.2 Metric Logging Structure

  • Train/Validation Metrics: {phase}/{metric_name}
    • 예: train/loss, val/accuracy
  • Class-wise Metrics: metrics/{phase}/class_metrics
    • 예: metrics/train/f1_per_class
  • Visualization: metrics/{phase}/{plot_type}
    • 예: metrics/val/confusion_matrix

3.3 Logging Timing

  • Epoch-wise Metrics: 매 에폭 종료 시
  • Class-wise Performance: validation 단계 종료 시
  • Visualization Results: 학습 완료 시점
  • Experiment Settings: 실험 시작 시점

IV. Data Pipeline

1. Data Processing

1.1 Data Loading Settings

data:
  path: "data/raw"
  path_meta: "data/meta.csv"

2. Augmentation Strategies

2.1 Basic Augmentation

data:
  augmentation: "basic"
  • RandomHorizontalFlip
  • RandomRotation
  • RandomResizedCrop
  • ColorJitter

2.2 Advanced Augmentation

data:
  augmentation: "advanced"
  aug_params:
    scale_factor: 1.0  # augmentation 강도 조절 (1.0이 기본)
    prob_factor: 1.0   # augmentation 적용 확률 조절 (1.0이 기본)
  • Basic Augmentation +
  • RandomAffine
  • RandomPerspective
  • RandomErasing

Default Parameters (scale_factor=1.0, prob_factor=1.0)

  • RandomHorizontalFlip(p=0.5)
  • RandomRotation(degrees=15)
  • RandomResizedCrop(scale=(0.85, 1.0))
  • ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1)
  • RandomAffine(degrees=10, translate=(0.1, 0.1))
  • RandomPerspective(distortion_scale=0.2, p=0.5)
  • RandomErasing(p=0.3, scale=(0.02, 0.2))

Augmentation Strength Control

  • scale_factor: augmentation 강도 조절

    • 1.0: 기본 강도
    • 1.0 < scale_factor: 더 강한 augmentation (예: 1.5배 강한 변형)
    • scale_factor < 1.0: 더 약한 augmentation (예: 0.8배 약한 변형)
  • prob_factor: augmentation 적용 확률 조절

    • 1.0: 기본 확률
    • prob_factor < 1.0: 더 낮은 적용 확률 (예: 0.8배 낮은 확률)

3. Class Imbalance Handling

data:
  balance_strategy: "sampling"  # none, sampling, weighted_sampler, augmentation
  sampling:
    method: "over"  # under, over
    strategy: 1.0   # sampling ratio
  augmentation_sampling:
    strategy: "target"  # median, max, target
    target_count: 1000  # target strategy 사용시 목표 샘플 수

3.1 Available Strategies

1. Augmentation-based Balancing

data:
  balance_strategy: "augmentation"
  augmentation_sampling:
    strategy: "target"    # median, max, target
    target_count: 1000    # target strategy 사용시 목표 샘플 수
  • Strategy Options:
    • median: 중간값을 기준으로 증강
    • max: 최대 클래스 수에 맞춰 증강
    • target: 지정된 목표 수만큼 증강
  • 장점:
    • 데이터 증강을 통한 다양성 확보
    • 오버피팅 위험 감소
  • 단점:
    • 계산 비용 증가
    • 메모리 사용량 증가

2. Sampling-based Balancing

data:
  balance_strategy: "sampling"
  sampling:
    method: "over"  # under, over
    strategy: 1.0   # sampling ratio
  augmentation: "advanced"  # 선택적 augmentation 적용
  • Over Sampling: 소수 클래스 샘플을 복제하여 증가
  • Under Sampling: 다수 클래스 샘플을 줄여서 균형

3. Weighted Random Sampling

data:
  balance_strategy: "weighted_sampler"
  augmentation: "advanced"  # 선택적 augmentation 적용
  • 클래스별 가중치를 기반으로 샘플링
  • 소수 클래스에 더 높은 가중치 부여

3.2 Balancing + Augmentation 조합

1. Augmentation-based Balancing + Advanced Augmentation

  • 작동 방식:
    1. Augmentation을 통한 클래스 밸런싱
    2. Advanced Augmentation으로 추가 다양성 확보
  • 장점:
    • 데이터 다양성 최대화
    • 클래스 불균형 해소
  • 단점:
    • 높은 계산 비용
    • 큰 메모리 사용량

2. Weighted Sampler + Advanced Augmentation

  • 작동 방식:
    1. 클래스별 가중치로 배치 구성
    2. 선택된 샘플에 Augmentation 적용
  • 장점:
    • 메모리 효율적
    • 매 에폭마다 다른 조합으로 학습
    • Augmentation으로 데이터 다양성 확보
  • 단점:
    • 같은 샘플이 자주 반복될 수 있음
    • 배치 내 동일 이미지의 다른 augmentation 버전 존재 가능

3.3 실험 가이드

# 실험 1: Augmentation-based Balancing
data:
  balance_strategy: "augmentation"
  augmentation_sampling:
    strategy: "target"
    target_count: 1000
  augmentation: "advanced"
  aug_params:
    scale_factor: 1.0
    prob_factor: 1.0
# 실험 2: Weighted Sampler + Advanced Augmentation
data:
  balance_strategy: "weighted_sampler"
  augmentation: "advanced"
  aug_params:
    scale_factor: 1.0
    prob_factor: 1.0
# 실험 3: Over Sampling + Advanced Augmentation
data:
  balance_strategy: "sampling"
  sampling:
    method: "over"
  augmentation: "advanced"
  aug_params:
    scale_factor: 1.0
    prob_factor: 1.0

성능 비교 포인트

  • Validation Macro F1: 전체적인 성능 지표
  • Loss Curve: 학습 안정성 확인
  • Per-class Performance: 클래스별 성능 균형
  • Resource Usage: 학습 시간과 메모리 사용량

모니터링

  • Weights & Biases를 통한 실험 추적
  • 클래스별 성능 메트릭 모니터링
  • 리소스 사용량 비교

4. Validation Strategies

data:
  val_selection:
    enabled: true
    strategy: "balanced"  # none, random, balanced, test_similar
    similarity_metrics:  # test_similar 전략 사용시
      - "image_stats"   # 이미지 통계 기반
      - "feature_dist"  # 특징 분포 기반
      - "domain_score"  # 도메인 유사도

4.1 Strategy-specific Features

Random Split

  • 기본적인 무작위 분할 방식
  • 클래스 분포 유지되지 않을 수 있음

Balanced Split

  • 각 클래스에서 동일한 비율로 검증 데이터 선택
  • 클래스 불균형 문제 해결

Test-Similar Split

data:
  val_selection:
    strategy: "test_similar"
    similarity_metrics:
      - "image_stats"    # 이미지 통계량 기반 유사도
      - "feature_dist"   # 특징 분포 기반 유사도
      - "domain_score"   # 도메인 점수 기반 유사도
    test_similar:
      n_samples: 100     # 클래스당 선택할 샘플 수
      threshold: 0.8     # 유사도 임값

Image Stats 기반

  • 이미지 통계량(평균, 분산 등) 계산
  • 테스트 데이터와 유사한 통계 분포를 가진 샘플 선택

Feature Distribution 기반

  • 사전학습된 CNN으로 특징 추출
  • 테스트 데이터의 특징 분포와 유사한 샘플 선택

Domain Score 기반

  • 도메인 분류기를 통한 도메인 유사도 계산
  • 테스트 도메인과 유사한 특성을 가진 샘플 선택

4.2 검증 전략 선택 기준

  • 일반적인 경우: Balanced Split 권장
  • 도메인 갭이 큰 경우: Test-Similar Split 권장
  • 데이터가 충분한 경우: Random Split도 고려 가능

V. Model Development

1. Supported Architectures

1.1 ResNet Family

model:
  name: "resnet50"  # resnet18, resnet34, resnet50, resnet101
  pretrained: true
  • 이미지 크기 유연함 (224, 256, 512 등)
  • 잔차 연결을 통한 깊은 네트워크 학습

1.2 EfficientNet Family

model:
  name: "efficientnet_b0"  # b0~b7
  • efficientnet_b0 (224x224) ~ b7 (600x600)
  • 각 모델별 최적화된 이미지 크기 사용

1.3 Vision Transformer

model:
  name: "vit_base_patch16_224"  # base, small, large, tiny
  • 이미지 크기 224x224 고정
  • Attention 메커니즘 기반 이미지 처리

2. Model Configuration

2.1 Initialization Settings

model:
  init_method: "xavier_uniform"  # none, xavier_uniform, xavier_normal, kaiming_uniform, kaiming_normal
  init_params:
    gain: 1.0
    mode: "fan_in"  # fan_in, fan_out
    nonlinearity: "relu"

2.2 Regularization Settings

model:
  regularization:
    dropout: 0.2
    weight_decay: 0.0001
    label_smoothing: 0.1

3. Training Process

3.1 Basic Training Settings

train:
  epochs: 100
  batch_size: 32
  optimizer: "adamw"
  lr: 1e-4
  scheduler: "cosine"

3.2 Learning Rate Scheduling

  • Early Stopping
  • (WIP) (Learning Rate Scheduling) (Gradient Clipping)

VI. Advanced Features

1. Performance Optimization

1.1 Mixed Precision Training

train:
  mixed_precision:
    enabled: true
  • FP16 연산을 통한 학습 속도 향상
  • 메모리 사용량 감소

1.2 Early Stopping

train:
  early_stopping:
    enabled: true
    patience: 5
    min_delta: 0.001

1.3 Label Smoothing

model:
  regularization:
    label_smoothing: 0.1  # 0.0-1.0
  • 모델 일반화 성능 향상
  • 과적합 감소

Working Principle

  • Hard target (0 또는 1)을 Soft target으로 변환
  • 정답 레이블: 1 → (1 - α)
  • 오답 레이블: 0 → α/(K-1) # K: 클래스 수

Key Effects

  • Over-confidence 방지

    • 모델이 특정 클래스에 과도하게 확신하는 것을 방지
    • 더 부드러운 결정 경계 형성
  • Generalization Performance Improvement

    • 학습 데이터의 노이즈에 대한 강건성 증가
    • 테스트 데이터에 대한 성능 향상

Hyperparameter Selection

  • α = 0.1: 일반적으로 사용되는 기본값
  • α = 0.2: 노이즈가 많은 데이터셋
  • α = 0.05: 깨끗한 데이터셋

2. Domain Adaptation

2.1 Experiment Options

model:
  domain_adaptation:
    method: "none"  # none, tta, adabn, dann
    # Test-Time Augmentation (TTA)
    tta_steps: 10   # TTA 적용 시 반복 횟수
    tta_lr: 0.0001  # TTA 적용 시 learning rate
    # Adaptive Batch Normalization (AdaBN)
    adabn_momentum: 0.1  # BN 통계 업데이트 momentum
    # Domain Adversarial Training (DANN)
    lambda_domain: 1.0  # 도메인 적대적 손실 가중치

2.2 도메인 적응 기법 상세

Test-Time Augmentation (TTA)

  • 테스트 시점에서 augmentation을 통한 예측 앙상블
  • 여러 번의 augmentation으로 안정적인 예측
  • tta_steps: augmentation 반복 횟수
  • tta_lr: adaptation 학습률

Adaptive Batch Normalization (AdaBN)

  • 테스트 데이터의 통계로 BN 레이어 업데이트
  • 도메인 갭으로 인한 성능 저하 완화
  • adabn_momentum: 통계 업데이트 속도 조절

Domain Adversarial Training (DANN)

  • 도메인 불변 특징 학습을 위한 적대적 학습
  • 도메인 판별자를 통한 특징 정제
  • lambda_domain: 도메인 적대적 손실 가중치

2.3 사용 시나리오

  • TTA: Test Data의 변동이 큰 경우
  • AdaBN: Domain Gap으로 BN 통계 차이가 발생하는 경우
  • DANN: 충분한 Test Data로 Domain 학습이 가능한 경우

VII. Development Guide

1. Git Convention

1.1 Branch Management

  • main: Stable Code
  • baseline: Basic Code
  • dev: Development in Progress
  • feature/*: New Feature Development

1.2 Commit Convention

feat: 새로운 기능 추가
fix: 버그 수정
docs: 문서 수정
refactor: 코드 리팩토링
test: 테스트 코드
chore: 빌드 업무 수정

2. Troubleshooting

2.1 Logging System

  • Metric and Image Logging Conflict: Metrics logged every epoch, images logged after training completion
  • Key Naming Consistency: {phase}/{metric_name} format
  • Logging Timing Management: Separate logging times for metrics, images, and JSON logs

2.2 Memory Management

  • Enable Mixed Precision Training
  • Set appropriate batch size
  • Adjust num_workers

3. Examples

  • examples/baseline.ipynb: 기본 학습 예제 노트북
  • examples/baseline.py: 기본 학습 스크립트

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 3

  •  
  •  
  •