File size: 8,082 Bytes
0468ff5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
CNN Model for Spectrogram-based Classification
Deep learning approach using Mel-spectrograms as 2D images.
Best for high accuracy and detecting patterns humans can't define.
"""
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from pathlib import Path
from typing import Tuple, Optional, Union

import sys
sys.path.insert(0, str(Path(__file__).parent.parent))
from config import CNN_INPUT_CHANNELS, CNN_HIDDEN_DIMS, CNN_DROPOUT, MODELS_DIR


class SpectrogramCNN(nn.Module):
    """
    4-layer CNN for Mel-spectrogram classification.
    
    Architecture:
    - 4 convolutional blocks (conv + batch norm + relu + maxpool)
    - Global average pooling
    - Fully connected layers with dropout
    - Binary output (human vs AI)
    """
    
    def __init__(
        self,
        input_channels: int = CNN_INPUT_CHANNELS,
        hidden_dims: list = None,
        dropout: float = CNN_DROPOUT,
        input_height: int = 128,
        input_width: int = 128
    ):
        """
        Initialize the CNN.
        
        Args:
            input_channels: Number of input channels (1 for mono)
            hidden_dims: List of hidden dimensions for conv layers
            dropout: Dropout rate
            input_height: Height of input spectrogram (n_mels)
            input_width: Width of input spectrogram (time frames)
        """
        super().__init__()
        
        if hidden_dims is None:
            hidden_dims = CNN_HIDDEN_DIMS  # [32, 64, 128, 256]
        
        self.hidden_dims = hidden_dims
        self.dropout_rate = dropout
        
        # Convolutional blocks
        layers = []
        in_channels = input_channels
        
        for out_channels in hidden_dims:
            layers.extend([
                nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1),
                nn.BatchNorm2d(out_channels),
                nn.ReLU(inplace=True),
                nn.MaxPool2d(kernel_size=2, stride=2)
            ])
            in_channels = out_channels
        
        self.conv_layers = nn.Sequential(*layers)
        
        # Calculate feature size after convolutions
        # Each maxpool reduces size by 2, we have len(hidden_dims) pools
        reduced_height = input_height // (2 ** len(hidden_dims))
        reduced_width = input_width // (2 ** len(hidden_dims))
        feature_size = hidden_dims[-1] * reduced_height * reduced_width
        
        # Fully connected layers
        self.fc_layers = nn.Sequential(
            nn.Flatten(),
            nn.Linear(feature_size, 512),
            nn.ReLU(inplace=True),
            nn.Dropout(dropout),
            nn.Linear(512, 128),
            nn.ReLU(inplace=True),
            nn.Dropout(dropout),
            nn.Linear(128, 2)  # Binary classification
        )
        
        # Initialize weights
        self._init_weights()
    
    def _init_weights(self):
        """Initialize weights using He initialization."""
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
                if m.bias is not None:
                    nn.init.constant_(m.bias, 0)
            elif isinstance(m, nn.BatchNorm2d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)
            elif isinstance(m, nn.Linear):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
                nn.init.constant_(m.bias, 0)
    
    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
        Forward pass.
        
        Args:
            x: Input tensor (batch, channels, height, width)
            
        Returns:
            Logits tensor (batch, 2)
        """
        x = self.conv_layers(x)
        x = self.fc_layers(x)
        return x
    
    def predict_proba(self, x: torch.Tensor) -> torch.Tensor:
        """
        Get probability predictions.
        
        Args:
            x: Input tensor
            
        Returns:
            Probabilities tensor (batch, 2)
        """
        logits = self.forward(x)
        return F.softmax(logits, dim=1)


class CNNClassifier:
    """
    Wrapper class for CNN-based classification.
    Handles training, prediction, and model persistence.
    """
    
    def __init__(
        self,
        input_height: int = 128,
        input_width: int = 128,
        device: Optional[str] = None
    ):
        """
        Initialize the CNN classifier.
        
        Args:
            input_height: Spectrogram height
            input_width: Spectrogram width
            device: Device to use ('cuda', 'cpu', or None for auto)
        """
        self.input_height = input_height
        self.input_width = input_width
        
        if device is None:
            self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        else:
            self.device = torch.device(device)
        
        self.model = SpectrogramCNN(
            input_height=input_height,
            input_width=input_width
        ).to(self.device)
        
        self.is_fitted = False
    
    def predict(
        self,
        spectrograms: np.ndarray
    ) -> Tuple[np.ndarray, np.ndarray]:
        """
        Predict labels and probabilities.
        
        Args:
            spectrograms: Array of spectrograms (n_samples, height, width)
            
        Returns:
            Tuple of (predictions, probabilities)
        """
        self.model.eval()
        
        # Add channel dimension if needed
        if spectrograms.ndim == 3:
            spectrograms = spectrograms[:, np.newaxis, :, :]
        
        # Convert to tensor
        x = torch.FloatTensor(spectrograms).to(self.device)
        
        with torch.no_grad():
            probs = self.model.predict_proba(x)
            probs = probs.cpu().numpy()
        
        predictions = np.argmax(probs, axis=1)
        ai_probabilities = probs[:, 1]  # P(AI)
        
        return predictions, ai_probabilities
    
    def predict_single(
        self,
        spectrogram: np.ndarray
    ) -> Tuple[int, float]:
        """
        Predict for a single spectrogram.
        
        Args:
            spectrogram: Single spectrogram (height, width) or (1, height, width)
            
        Returns:
            Tuple of (prediction, probability)
        """
        if spectrogram.ndim == 2:
            spectrogram = spectrogram[np.newaxis, :, :]
        
        predictions, probabilities = self.predict(spectrogram)
        return int(predictions[0]), float(probabilities[0])
    
    def save(self, path: Optional[Union[str, Path]] = None) -> Path:
        """
        Save the trained model.
        
        Args:
            path: Optional save path
            
        Returns:
            Path where model was saved
        """
        if path is None:
            path = MODELS_DIR / "cnn_model.pth"
        
        path = Path(path)
        path.parent.mkdir(parents=True, exist_ok=True)
        
        torch.save({
            "model_state_dict": self.model.state_dict(),
            "input_height": self.input_height,
            "input_width": self.input_width,
            "is_fitted": self.is_fitted
        }, path)
        
        return path
    
    @classmethod
    def load(cls, path: Union[str, Path], device: Optional[str] = None) -> "CNNClassifier":
        """
        Load a trained model.
        
        Args:
            path: Path to saved model
            device: Device to load to
            
        Returns:
            Loaded classifier
        """
        checkpoint = torch.load(path, map_location=device or "cpu")
        
        instance = cls(
            input_height=checkpoint["input_height"],
            input_width=checkpoint["input_width"],
            device=device
        )
        instance.model.load_state_dict(checkpoint["model_state_dict"])
        instance.is_fitted = checkpoint["is_fitted"]
        
        return instance