File size: 6,788 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 | """
Model Trainer for VocalSense
Trains Traditional ML and CNN models on the audio dataset.
"""
import numpy as np
from pathlib import Path
from typing import Dict, Optional, Tuple
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, classification_report
import time
import sys
sys.path.insert(0, str(Path(__file__).parent.parent))
from config import MODELS_DIR, EPOCHS, BATCH_SIZE, LEARNING_RATE, EARLY_STOPPING_PATIENCE
from models.traditional import FeatureBasedClassifier
from training.dataset import AudioDataset
class Trainer:
"""
Trainer for VocalSense models.
Supports training:
- Traditional ML (Random Forest, SVM)
- CNN (coming soon - requires spectrogram dataset)
"""
def __init__(
self,
model_type: str = "random_forest",
epochs: int = EPOCHS,
save_dir: Optional[Path] = None
):
"""
Initialize trainer.
Args:
model_type: 'random_forest' or 'svm'
epochs: Number of epochs (for future CNN training)
save_dir: Directory to save trained models
"""
self.model_type = model_type
self.epochs = epochs
self.save_dir = Path(save_dir) if save_dir else MODELS_DIR
self.save_dir.mkdir(parents=True, exist_ok=True)
self.model = None
self.history = {
'train_acc': [],
'val_acc': [],
'train_loss': [],
'val_loss': []
}
def train(
self,
X_train: np.ndarray,
y_train: np.ndarray,
X_val: Optional[np.ndarray] = None,
y_val: Optional[np.ndarray] = None
) -> FeatureBasedClassifier:
"""
Train the model.
Args:
X_train: Training features
y_train: Training labels
X_val: Validation features (optional)
y_val: Validation labels (optional)
Returns:
Trained classifier
"""
print(f"\n{'='*50}")
print(f"Training {self.model_type.upper()} model")
print(f"{'='*50}")
print(f"Training samples: {len(y_train)}")
if y_val is not None:
print(f"Validation samples: {len(y_val)}")
start_time = time.time()
# Create and train model
self.model = FeatureBasedClassifier(classifier_type=self.model_type)
self.model.fit(X_train, y_train)
train_time = time.time() - start_time
print(f"\nTraining completed in {train_time:.2f} seconds")
# Evaluate on training set
train_preds, train_probs = self.model.predict(X_train)
train_acc = accuracy_score(y_train, train_preds)
print(f"Training accuracy: {train_acc:.4f}")
# Evaluate on validation set
if X_val is not None and y_val is not None:
val_preds, val_probs = self.model.predict(X_val)
val_acc = accuracy_score(y_val, val_preds)
print(f"Validation accuracy: {val_acc:.4f}")
self.history['val_acc'].append(val_acc)
self.history['train_acc'].append(train_acc)
return self.model
def evaluate(
self,
X_test: np.ndarray,
y_test: np.ndarray,
verbose: bool = True
) -> Dict[str, float]:
"""
Evaluate model on test set.
Args:
X_test: Test features
y_test: Test labels
verbose: Whether to print detailed report
Returns:
Dictionary of metrics
"""
if self.model is None:
raise RuntimeError("Model not trained. Call train() first.")
predictions, probabilities = self.model.predict(X_test)
metrics = {
'accuracy': accuracy_score(y_test, predictions),
'precision': precision_score(y_test, predictions, zero_division=0),
'recall': recall_score(y_test, predictions, zero_division=0),
'f1': f1_score(y_test, predictions, zero_division=0)
}
if verbose:
print(f"\n{'='*50}")
print("TEST SET EVALUATION")
print(f"{'='*50}")
print(f"Accuracy: {metrics['accuracy']:.4f}")
print(f"Precision: {metrics['precision']:.4f}")
print(f"Recall: {metrics['recall']:.4f}")
print(f"F1 Score: {metrics['f1']:.4f}")
print(f"\nClassification Report:")
print(classification_report(
y_test, predictions,
target_names=['Human/Real', 'AI/Fake']
))
return metrics
def save_model(self, filename: Optional[str] = None) -> Path:
"""
Save trained model.
Args:
filename: Optional filename
Returns:
Path to saved model
"""
if self.model is None:
raise RuntimeError("Model not trained. Call train() first.")
if filename is None:
filename = f"traditional_{self.model_type}.pkl"
save_path = self.save_dir / filename
self.model.save(save_path)
print(f"\nModel saved to: {save_path}")
return save_path
def train_full_pipeline(
model_type: str = "random_forest",
epochs: int = 50,
data_dir: Optional[Path] = None
) -> Tuple[FeatureBasedClassifier, Dict[str, float]]:
"""
Full training pipeline: load data, train, evaluate, save.
Args:
model_type: 'random_forest' or 'svm'
epochs: Number of epochs
data_dir: Data directory
Returns:
Tuple of (trained model, test metrics)
"""
print("\n" + "="*60)
print(" VocalSense Training Pipeline")
print("="*60)
# Load dataset
print("\n[1/4] Loading dataset...")
dataset = AudioDataset(data_dir=data_dir)
splits = dataset.get_splits()
X_train, y_train = splits['train']
X_val, y_val = splits['val']
X_test, y_test = splits['test']
# Train model
print("\n[2/4] Training model...")
trainer = Trainer(model_type=model_type, epochs=epochs)
model = trainer.train(X_train, y_train, X_val, y_val)
# Evaluate
print("\n[3/4] Evaluating model...")
metrics = trainer.evaluate(X_test, y_test)
# Save
print("\n[4/4] Saving model...")
trainer.save_model()
print("\n" + "="*60)
print(" Training Complete!")
print("="*60)
print(f" Final Test Accuracy: {metrics['accuracy']:.2%}")
print("="*60 + "\n")
return model, metrics
if __name__ == "__main__":
train_full_pipeline()
|