vs / models /cnn.py
devmm03's picture
intial commit
0468ff5
Raw History Blame Contribute Delete
8.08 kB
"""
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