File size: 9,498 Bytes
ff0e79e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
"""

Training utilities and metrics

Implements Critical Fix #9: Dataset-Aware Metric Computation

"""

import torch
import numpy as np
from typing import Dict, List, Optional
from sklearn.metrics import (
    accuracy_score, f1_score, precision_score, recall_score,
    confusion_matrix
)


class SegmentationMetrics:
    """

    Segmentation metrics (IoU, Dice)

    Only computed for datasets with pixel masks (Critical Fix #9)

    """
    
    def __init__(self):
        """Initialize metrics"""
        self.reset()
    
    def reset(self):
        """Reset all metrics"""
        self.intersection = 0
        self.union = 0
        self.pred_sum = 0
        self.target_sum = 0
        self.total_samples = 0
    
    def update(self, 

               pred: torch.Tensor, 

               target: torch.Tensor,

               has_pixel_mask: bool = True):
        """

        Update metrics with batch

        

        Args:

            pred: Predicted probabilities (B, 1, H, W)

            target: Ground truth masks (B, 1, H, W)

            has_pixel_mask: Whether to compute metrics (Critical Fix #9)

        """
        if not has_pixel_mask:
            return
        
        # Binarize predictions
        pred_binary = (pred > 0.5).float()
        
        # Compute intersection and union
        intersection = (pred_binary * target).sum().item()
        union = pred_binary.sum().item() + target.sum().item() - intersection
        
        self.intersection += intersection
        self.union += union
        self.pred_sum += pred_binary.sum().item()
        self.target_sum += target.sum().item()
        self.total_samples += pred.shape[0]
    
    def compute(self) -> Dict[str, float]:
        """

        Compute final metrics

        

        Returns:

            Dictionary with IoU, Dice, Precision, Recall

        """
        # IoU (Jaccard)
        iou = self.intersection / (self.union + 1e-8)
        
        # Dice (F1)
        dice = (2 * self.intersection) / (self.pred_sum + self.target_sum + 1e-8)
        
        # Precision
        precision = self.intersection / (self.pred_sum + 1e-8)
        
        # Recall
        recall = self.intersection / (self.target_sum + 1e-8)
        
        return {
            'iou': iou,
            'dice': dice,
            'precision': precision,
            'recall': recall
        }


class ClassificationMetrics:
    """Classification metrics for forgery type classification"""
    
    def __init__(self, num_classes: int = 3):
        """

        Initialize metrics

        

        Args:

            num_classes: Number of forgery types

        """
        self.num_classes = num_classes
        self.reset()
    
    def reset(self):
        """Reset all metrics"""
        self.predictions = []
        self.targets = []
        self.confidences = []
    
    def update(self, 

               pred: np.ndarray, 

               target: np.ndarray,

               confidence: Optional[np.ndarray] = None):
        """

        Update metrics with predictions

        

        Args:

            pred: Predicted class indices

            target: Ground truth class indices

            confidence: Optional prediction confidences

        """
        self.predictions.extend(pred.tolist())
        self.targets.extend(target.tolist())
        if confidence is not None:
            self.confidences.extend(confidence.tolist())
    
    def compute(self) -> Dict[str, float]:
        """

        Compute final metrics

        

        Returns:

            Dictionary with Accuracy, F1, Precision, Recall

        """
        if len(self.predictions) == 0:
            return {
                'accuracy': 0.0,
                'f1_macro': 0.0,
                'f1_weighted': 0.0,
                'precision': 0.0,
                'recall': 0.0
            }
        
        preds = np.array(self.predictions)
        targets = np.array(self.targets)
        
        # Accuracy
        accuracy = accuracy_score(targets, preds)
        
        # F1 score (macro and weighted)
        f1_macro = f1_score(targets, preds, average='macro', zero_division=0)
        f1_weighted = f1_score(targets, preds, average='weighted', zero_division=0)
        
        # Precision and Recall
        precision = precision_score(targets, preds, average='macro', zero_division=0)
        recall = recall_score(targets, preds, average='macro', zero_division=0)
        
        # Confusion matrix
        cm = confusion_matrix(targets, preds, labels=range(self.num_classes))
        
        return {
            'accuracy': accuracy,
            'f1_macro': f1_macro,
            'f1_weighted': f1_weighted,
            'precision': precision,
            'recall': recall,
            'confusion_matrix': cm.tolist()
        }


class MetricsTracker:
    """Track all metrics during training"""
    
    def __init__(self, config):
        """

        Initialize metrics tracker

        

        Args:

            config: Configuration object

        """
        self.config = config
        self.num_classes = config.get('data.num_classes', 3)
        
        self.seg_metrics = SegmentationMetrics()
        self.cls_metrics = ClassificationMetrics(self.num_classes)
        
        self.history = {
            'train_loss': [],
            'val_loss': [],
            'train_iou': [],
            'val_iou': [],
            'train_dice': [],
            'val_dice': [],
            'train_precision': [],
            'val_precision': [],
            'train_recall': [],
            'val_recall': []
        }
    
    def reset(self):
        """Reset metrics for new epoch"""
        self.seg_metrics.reset()
        self.cls_metrics.reset()
    
    def update_segmentation(self, 

                           pred: torch.Tensor, 

                           target: torch.Tensor,

                           dataset_name: str):
        """Update segmentation metrics (dataset-aware)"""
        has_pixel_mask = self.config.should_compute_localization_metrics(dataset_name)
        self.seg_metrics.update(pred, target, has_pixel_mask)
    
    def update_classification(self, 

                             pred: np.ndarray, 

                             target: np.ndarray,

                             confidence: Optional[np.ndarray] = None):
        """Update classification metrics"""
        self.cls_metrics.update(pred, target, confidence)
    
    def compute_all(self) -> Dict[str, float]:
        """Compute all metrics"""
        seg = self.seg_metrics.compute()
        
        # Only include classification metrics if they have data
        if len(self.cls_metrics.predictions) > 0:
            cls = self.cls_metrics.compute()
            # Prefix classification metrics to avoid collision
            cls_prefixed = {f'cls_{k}': v for k, v in cls.items()}
            return {**seg, **cls_prefixed}
        
        return seg
    
    def log_epoch(self, epoch: int, phase: str, loss: float, metrics: Dict):
        """Log metrics for epoch"""
        prefix = f'{phase}_'
        
        self.history[f'{phase}_loss'].append(loss)
        
        if 'iou' in metrics:
            self.history[f'{phase}_iou'].append(metrics['iou'])
        if 'dice' in metrics:
            self.history[f'{phase}_dice'].append(metrics['dice'])
        if 'precision' in metrics:
            self.history[f'{phase}_precision'].append(metrics['precision'])
        if 'recall' in metrics:
            self.history[f'{phase}_recall'].append(metrics['recall'])
    
    def get_history(self) -> Dict:
        """Get full training history"""
        return self.history


class EarlyStopping:
    """Early stopping to prevent overfitting"""
    
    def __init__(self, 

                 patience: int = 10,

                 min_delta: float = 0.001,

                 mode: str = 'max'):
        """

        Initialize early stopping

        

        Args:

            patience: Number of epochs to wait

            min_delta: Minimum improvement required

            mode: 'min' for loss, 'max' for metrics

        """
        self.patience = patience
        self.min_delta = min_delta
        self.mode = mode
        
        self.counter = 0
        self.best_value = None
        self.should_stop = False
    
    def __call__(self, value: float) -> bool:
        """

        Check if training should stop

        

        Args:

            value: Current metric value

        

        Returns:

            True if should stop

        """
        if self.best_value is None:
            self.best_value = value
            return False
        
        if self.mode == 'max':
            improved = value > self.best_value + self.min_delta
        else:
            improved = value < self.best_value - self.min_delta
        
        if improved:
            self.best_value = value
            self.counter = 0
        else:
            self.counter += 1
        
        if self.counter >= self.patience:
            self.should_stop = True
        
        return self.should_stop


def get_metrics_tracker(config) -> MetricsTracker:
    """Factory function for metrics tracker"""
    return MetricsTracker(config)