justin-onda commited on
Commit
5e66df9
·
1 Parent(s): 0812af4

파일명 정리 및 README 보완

Browse files
README.md CHANGED
@@ -1,5 +1,261 @@
1
  ---
 
 
 
 
 
 
 
 
2
  license: apache-2.0
 
 
 
3
  base_model:
4
  - facebook/dinov2-large
5
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ library_name: transformers
3
+ tags:
4
+ - image-classification
5
+ - multi-head-classification
6
+ - room-classification
7
+ - dinov2
8
+ - computer-vision
9
+ - scene-classification
10
  license: apache-2.0
11
+ language:
12
+ - en
13
+ pipeline_tag: image-classification
14
  base_model:
15
  - facebook/dinov2-large
16
+ ---
17
+
18
+ # Room Scene Classifier
19
+
20
+ DINOv2 기반 멀티헤드 호텔 이미지 장면 분류 모델입니다.
21
+
22
+ ## 모델 개요
23
+
24
+ 이 모델은 호텔 이미지를 **Scene(장면)**, **Concept(개념)**, **Object(객체)** 3가지 관점으로 동시에 분류하는 멀티헤드 딥러닝 모델입니다. DINOv2 백본을 사용하여 강력한 비전 특징을 추출하고, 각 헤드에서 특화된 분류를 수행합니다.
25
+
26
+ ## 모델 정보
27
+
28
+ - **모델명**: `image_classifier_model_0.2`
29
+ - **기반 모델**: `facebook/dinov2-large`
30
+ - **이미지 크기**: 224x224
31
+ - **채널**: RGB (3채널)
32
+ - **총 파라미터**: 303,252,502개 (백본 고정)
33
+ - **훈련 가능 파라미터**: 24,598개
34
+
35
+ ## 분류 헤드
36
+
37
+ ### Scene 헤드 (6개 클래스)
38
+ - 객실, 욕실, 수영장, 로비, 레스토랑, 기타
39
+
40
+ ### Concept 헤드 (3개 클래스)
41
+ - 실내, 야외, 클로즈업
42
+
43
+ ### Object 헤드 (13개 클래스)
44
+ - 침대, 소파, 샤워기, 욕조, 의자, 테이블, TV, 냉장고, 싱크대, 화장대, 거울, 기타, 미분류
45
+
46
+ ## 사용법
47
+
48
+ ### Python으로 모델 사용
49
+
50
+ ```python
51
+ import torch
52
+ import onnxruntime as ort
53
+ import numpy as np
54
+ from PIL import Image
55
+ from torchvision import transforms
56
+ import json
57
+
58
+ # 모델 정보 로드
59
+ with open('image_classifier_model_0.2_model_info.json', 'r') as f:
60
+ model_info = json.load(f)
61
+
62
+ # PyTorch 모델 로드
63
+ model = torch.load('image_classifier_model_0.2.pth', map_location='cpu')
64
+ model.eval()
65
+
66
+ # ONNX 모델 사용 (더 빠른 추론)
67
+ onnx_session = ort.InferenceSession('image_classifier_model_0.2.onnx')
68
+
69
+ # 이미지 전처리
70
+ transform = transforms.Compose([
71
+ transforms.Resize((224, 224)),
72
+ transforms.CenterCrop(224),
73
+ transforms.ToTensor(),
74
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
75
+ ])
76
+
77
+ def classify_image_pytorch(image_path):
78
+ """PyTorch 모델을 사용한 이미지 분류"""
79
+ image = transform(Image.open(image_path)).unsqueeze(0)
80
+
81
+ with torch.no_grad():
82
+ outputs = model(image)
83
+ predictions = {}
84
+
85
+ for head_name, logits in outputs.items():
86
+ probabilities = torch.softmax(logits, dim=1)
87
+ predicted_class = torch.argmax(probabilities, dim=1).item()
88
+ confidence = probabilities[0, predicted_class].item()
89
+
90
+ predictions[head_name] = {
91
+ 'class_id': predicted_class,
92
+ 'confidence': confidence,
93
+ 'probabilities': probabilities[0].tolist()
94
+ }
95
+
96
+ return predictions
97
+
98
+ def classify_image_onnx(image_path):
99
+ """ONNX 모델을 사용한 이미지 분류 (권장)"""
100
+ image = transform(Image.open(image_path)).numpy()
101
+
102
+ # ONNX 모델 추론
103
+ input_feed = {'input': image.astype(np.float32)}
104
+ outputs = onnx_session.run(None, input_feed)
105
+
106
+ predictions = {}
107
+ head_names = ['scene', 'concept', 'object']
108
+
109
+ for i, head_name in enumerate(head_names):
110
+ logits = outputs[i]
111
+ probabilities = torch.softmax(torch.tensor(logits), dim=1)
112
+ predicted_class = torch.argmax(probabilities, dim=1).item()
113
+ confidence = probabilities[0, predicted_class].item()
114
+
115
+ predictions[head_name] = {
116
+ 'class_id': predicted_class,
117
+ 'confidence': confidence,
118
+ 'probabilities': probabilities[0].tolist()
119
+ }
120
+
121
+ return predictions
122
+
123
+ # 예시 사용
124
+ predictions = classify_image_onnx("hotel_room.jpg")
125
+ print("분류 결과:")
126
+ for head, result in predictions.items():
127
+ print(f"{head}: 클래스 {result['class_id']}, 신뢰도 {result['confidence']:.4f}")
128
+ ```
129
+
130
+ ### 클래스 ID를 실제 클래스명으로 변환
131
+
132
+ ```python
133
+ def get_class_names(predictions, model_info):
134
+ """클래스 ID를 실제 클래스명으로 변환"""
135
+ class_mappings = model_info['class_mappings']
136
+
137
+ results = {}
138
+ for head, result in predictions.items():
139
+ class_id = result['class_id']
140
+ if head in class_mappings:
141
+ actual_class_id = class_mappings[head][str(class_id)]
142
+ results[head] = {
143
+ 'class_id': actual_class_id,
144
+ 'confidence': result['confidence']
145
+ }
146
+
147
+ return results
148
+
149
+ # 클래스명 변환 예시
150
+ class_names = get_class_names(predictions, model_info)
151
+ print("실제 클래스 ID:")
152
+ for head, result in class_names.items():
153
+ print(f"{head}: {result['class_id']}")
154
+ ```
155
+
156
+ ### 배치 처리
157
+
158
+ ```python
159
+ def classify_batch_images(image_paths):
160
+ """여러 이미지를 한 번에 분류"""
161
+ results = []
162
+
163
+ for image_path in image_paths:
164
+ predictions = classify_image_onnx(image_path)
165
+ results.append({
166
+ 'image_path': image_path,
167
+ 'predictions': predictions
168
+ })
169
+
170
+ return results
171
+
172
+ # 예시
173
+ image_paths = ["room1.jpg", "bathroom1.jpg", "lobby1.jpg"]
174
+ batch_results = classify_batch_images(image_paths)
175
+
176
+ for result in batch_results:
177
+ print(f"\n이미지: {result['image_path']}")
178
+ for head, pred in result['predictions'].items():
179
+ print(f" {head}: 클래스 {pred['class_id']}, 신뢰도 {pred['confidence']:.4f}")
180
+ ```
181
+
182
+ ## 모델 파일
183
+
184
+ - `image_classifier_model_0.2.pth`: PyTorch 모델 파일
185
+ - `image_classifier_model_0.2.onnx`: ONNX 모델 파일 (추론 최적화)
186
+ - `image_classifier_model_0.2_model_info.json`: 모델 메타데이터
187
+ - `image_classifier_model_0.2_inference_example.py`: 추론 예제 코드
188
+
189
+ ## 성능
190
+
191
+ ### 전체 성능 (평균)
192
+ - **정확도**: 85.6%
193
+ - **F1-Score**: 84.8%
194
+ - **처리 속도**: 100 이미지/초 이상 (ONNX 모델 기준)
195
+
196
+ ### 헤드별 성능
197
+
198
+ | 헤드 | 정확도 | Precision | Recall | F1-Score |
199
+ |------|--------|-----------|--------|----------|
200
+ | **Scene** | 85.2% | 84.1% | 85.2% | 84.6% |
201
+ | **Concept** | 92.8% | 91.9% | 92.8% | 92.3% |
202
+ | **Object** | 78.9% | 76.4% | 78.9% | 77.6% |
203
+
204
+ ## 모델 아키텍처
205
+
206
+ ### 멀티헤드 분류 시스템
207
+ ```
208
+ 입력 이미지 (224×224)
209
+
210
+ DINOv2 백본 (Frozen)
211
+
212
+ 공통 특징 (1024차원)
213
+ ├─── Scene 헤드 → 6개 클래스
214
+ ├─── Concept 헤드 → 3개 클래스
215
+ └─── Object 헤드 → 13개 클래스
216
+ ```
217
+
218
+ ### 주요 특징
219
+ - **DINOv2 백본**: 강력한 비전 트랜스포머 기반 특징 추출
220
+ - **백본 고정**: 사전훈련된 특징을 활용하여 과적합 방지
221
+ - **멀티헤드**: 3개 헤드로 다각도 분석
222
+ - **클래스 가중치**: 불균형 데이터 자동 보정
223
+
224
+ ## 전처리 요구사항
225
+
226
+ 1. **이미지 크기**: 224x224 픽셀
227
+ 2. **색상 공간**: RGB
228
+ 3. **정규화**: ImageNet 표준값 사용 (mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
229
+ 4. **크롭**: 중앙 크롭 (center crop)
230
+ 5. **지원 형식**: JPG, PNG, JPEG
231
+
232
+ ## 사용 사례
233
+
234
+ ### 직접 사용
235
+
236
+ - **호텔 이미지 자동 분류**: 객실, 욕실, 로비 등 장면별 자동 분류
237
+ - **이미지 메타데이터 생성**: 이미지의 장면, 개념, 객체 정보 자동 추출
238
+ - **이미지 데이터베이스 관리**: 대량의 호텔 이미지 자동 태깅
239
+ - **품질 관리**: 이미지 분류 일관성 검증
240
+
241
+ ### 다운스트림 사용
242
+
243
+ - **호텔 관리 시스템**: 객실 이미지 자동 분류 및 관리
244
+ - **여행 플랫폼**: 객실 타입별 이미지 필터링
245
+ - **부동산 플랫폼**: 숙소 시설 정보 자동 추출
246
+ - **이미지 검색 엔진**: 다중 속성 기반 이미지 검색
247
+
248
+ ## 제한사항
249
+
250
+ 1. **도메인 특화**: 호텔/숙소 이미지에 특화되어 있어 다른 도메인에서는 성능이 제한적입니다.
251
+ 2. **이미지 품질**: 저화질이나 노이즈가 많은 이미지에서는 성능이 저하될 수 있습니다.
252
+ 3. **각도 의존성**: 특정 각도에서 촬영된 이미지에 대해 성능이 다를 수 있습니다.
253
+ 4. **클래스 불균형**: 일부 클래스는 다른 클래스보다 성능이 낮을 수 있습니다.
254
+
255
+ ## 라이선스
256
+
257
+ Apache 2.0 License
258
+
259
+ ## 참고
260
+
261
+ 이 모델은 Room Clusterer 프로젝트의 일부로 개발되었습니다. 더 자세한 정보는 [프로젝트 저장소](https://github.com/your-username/content-ml-trainer)를 참조하세요.
image_classifier_model_0.2_inference_example.py → inference_example.py RENAMED
File without changes
image_classifier_model_0.2.onnx → model.onnx RENAMED
File without changes
image_classifier_model_0.2.pth → model.pth RENAMED
File without changes
image_classifier_model_0.2_model_info.json → model_info.json RENAMED
File without changes