vs / models /traditional.py
devmm03's picture
intial commit
0468ff5
Raw History Blame Contribute Delete
6.31 kB
"""
Traditional ML Classifiers
Feature-based classification using SVM and Random Forest.
Best for interpretability - can explain WHY a voice is flagged as AI.
"""
import numpy as np
import pickle
from pathlib import Path
from typing import Dict, Tuple, Optional, Union, List
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
import sys
sys.path.insert(0, str(Path(__file__).parent.parent))
from config import SVM_KERNEL, RF_N_ESTIMATORS, MODELS_DIR
class FeatureBasedClassifier:
"""
Traditional ML classifier for AI voice detection.
Uses extracted features (spectral, MFCC, prosodic) as input.
Supports SVM and Random Forest classifiers.
"""
def __init__(
self,
classifier_type: str = "random_forest",
**kwargs
):
"""
Initialize the classifier.
Args:
classifier_type: 'svm' or 'random_forest'
**kwargs: Additional classifier parameters
"""
self.classifier_type = classifier_type
self.scaler = StandardScaler()
self.is_fitted = False
if classifier_type == "svm":
self.classifier = SVC(
kernel=kwargs.get("kernel", SVM_KERNEL),
probability=True,
C=kwargs.get("C", 1.0),
gamma=kwargs.get("gamma", "scale"),
random_state=42
)
elif classifier_type == "random_forest":
self.classifier = RandomForestClassifier(
n_estimators=kwargs.get("n_estimators", RF_N_ESTIMATORS),
max_depth=kwargs.get("max_depth", None),
min_samples_split=kwargs.get("min_samples_split", 2),
random_state=42,
n_jobs=-1
)
else:
raise ValueError(f"Unknown classifier type: {classifier_type}")
# Create pipeline
self.pipeline = Pipeline([
("scaler", self.scaler),
("classifier", self.classifier)
])
def fit(
self,
features: np.ndarray,
labels: np.ndarray
) -> "FeatureBasedClassifier":
"""
Train the classifier.
Args:
features: Feature matrix (n_samples, n_features)
labels: Binary labels (0=human, 1=AI)
Returns:
Self
"""
self.pipeline.fit(features, labels)
self.is_fitted = True
return self
def predict(
self,
features: np.ndarray
) -> Tuple[np.ndarray, np.ndarray]:
"""
Predict labels and probabilities.
Args:
features: Feature matrix (n_samples, n_features)
Returns:
Tuple of (predictions, probabilities)
"""
if not self.is_fitted:
raise RuntimeError("Classifier not fitted. Call fit() first.")
predictions = self.pipeline.predict(features)
probabilities = self.pipeline.predict_proba(features)[:, 1] # P(AI)
return predictions, probabilities
def predict_single(
self,
features: np.ndarray
) -> Tuple[int, float]:
"""
Predict for a single sample.
Args:
features: Feature vector (n_features,)
Returns:
Tuple of (prediction, probability)
"""
features_2d = features.reshape(1, -1)
predictions, probabilities = self.predict(features_2d)
return int(predictions[0]), float(probabilities[0])
def get_feature_importance(self) -> Optional[Dict[str, float]]:
"""
Get feature importance (only for Random Forest).
Returns:
Dictionary mapping feature index to importance,
or None if not applicable
"""
if self.classifier_type != "random_forest":
return None
if not self.is_fitted:
return None
importances = self.classifier.feature_importances_
return {f"feature_{i}": float(imp) for i, imp in enumerate(importances)}
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 / f"traditional_{self.classifier_type}.pkl"
path = Path(path)
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "wb") as f:
pickle.dump({
"classifier_type": self.classifier_type,
"pipeline": self.pipeline,
"is_fitted": self.is_fitted
}, f)
return path
@classmethod
def load(cls, path: Union[str, Path]) -> "FeatureBasedClassifier":
"""
Load a trained model.
Args:
path: Path to saved model
Returns:
Loaded classifier
"""
with open(path, "rb") as f:
data = pickle.load(f)
instance = cls(classifier_type=data["classifier_type"])
instance.pipeline = data["pipeline"]
instance.scaler = data["pipeline"].named_steps["scaler"]
instance.classifier = data["pipeline"].named_steps["classifier"]
instance.is_fitted = data["is_fitted"]
return instance
def create_feature_vector(
spectral_features: Dict[str, float],
mfcc_features: Dict[str, float],
prosodic_features: Dict[str, float]
) -> np.ndarray:
"""
Combine all features into a single vector.
Args:
spectral_features: From spectral extraction
mfcc_features: From MFCC extraction
prosodic_features: From prosodic extraction
Returns:
Combined feature vector
"""
all_features = {}
all_features.update(spectral_features)
all_features.update(mfcc_features)
all_features.update(prosodic_features)
return np.array(list(all_features.values()))