Download training/trainer.py from devmm03/vs: direct link, hf CLI and curl.
- Browser
- Download file 6.79 kB
-
https://huggingface.co/spaces/devmm03/vs/resolve/main/training/trainer.py
- Command line
-
hf download hf://spaces/devmm03/vs/training/trainer.py
-
curl -L -o trainer.py https://huggingface.co/spaces/devmm03/vs/resolve/main/training/trainer.py
6.79 kB
| """ | |
| 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() | |