help@rskworld.in +91 93305 39277
RSK World
  • Home
  • Development
    • Web Development
    • Mobile Apps
    • Software
    • Games
    • Project
  • Technologies
    • Data Science
    • AI Development
    • Cloud Development
    • Blockchain
    • Cyber Security
    • Dev Tools
    • Testing Tools
  • Blog
  • About
  • Contact

Theme Settings

Color Scheme
Display Options
Font Size
100%
Back to Project
RSK World
music-classification
/
utils
RSK World
music-classification
Music Classification Dataset - Genre Classification + Music AI + Audio ML
utils
  • __pycache__
  • __init__.py1.6 KB
  • advanced_features.py8.3 KB
  • audio_augmentation.py6.3 KB
  • audio_processor.py5.5 KB
  • feature_extractor.py6.7 KB
  • model_comparison.py8.8 KB
  • realtime_processor.py8.8 KB
model_comparison.py
utils/model_comparison.py
Raw Download
Find: Go to:
"""
Model Comparison Utility for Music Classification

Project: Music Classification Dataset
Author: Molla Samser
Company: RSK World
Designer & Tester: Rima Khatun
Website: https://rskworld.in
Email: help@rskworld.in, support@rskworld.in
Phone: +91 93305 39277
Description: Compare different ML models for music genre classification
License: Educational Purpose Only
"""

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.tree import DecisionTreeClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
from sklearn.metrics import confusion_matrix, classification_report
import time
import warnings
warnings.filterwarnings('ignore')


class ModelComparator:
    """
    Compare multiple ML models for music genre classification
    
    Author: Molla Samser (RSK World)
    Website: https://rskworld.in
    Email: help@rskworld.in
    Phone: +91 93305 39277
    """
    
    def __init__(self):
        """Initialize Model Comparator"""
        self.models = {}
        self.results = {}
        self.setup_models()
    
    def setup_models(self):
        """
        Setup all models for comparison
        
        Author: Molla Samser (RSK World)
        """
        self.models = {
            'Random Forest': RandomForestClassifier(n_estimators=100, random_state=42),
            'Gradient Boosting': GradientBoostingClassifier(n_estimators=100, random_state=42),
            'SVM (RBF)': SVC(kernel='rbf', random_state=42, probability=True),
            'SVM (Linear)': SVC(kernel='linear', random_state=42, probability=True),
            'KNN (k=5)': KNeighborsClassifier(n_neighbors=5),
            'KNN (k=7)': KNeighborsClassifier(n_neighbors=7),
            'Decision Tree': DecisionTreeClassifier(random_state=42),
            'Naive Bayes': GaussianNB(),
            'Logistic Regression': LogisticRegression(max_iter=1000, random_state=42)
        }
    
    def train_and_evaluate(self, X_train, y_train, X_test, y_test):
        """
        Train and evaluate all models
        
        Args:
            X_train: Training features
            y_train: Training labels
            X_test: Test features
            y_test: Test labels
        """
        print("="*70)
        print("Model Comparison - Music Genre Classification")
        print("Author: Molla Samser | Company: RSK World")
        print("="*70)
        print(f"\nTraining {len(self.models)} models...")
        print(f"Training samples: {len(X_train)}")
        print(f"Test samples: {len(X_test)}\n")
        
        for name, model in self.models.items():
            print(f"Training {name}...")
            
            # Train
            start_time = time.time()
            model.fit(X_train, y_train)
            train_time = time.time() - start_time
            
            # Predict
            start_time = time.time()
            y_pred = model.predict(X_test)
            predict_time = time.time() - start_time
            
            # Metrics
            accuracy = accuracy_score(y_test, y_pred)
            precision = precision_score(y_test, y_pred, average='weighted', zero_division=0)
            recall = recall_score(y_test, y_pred, average='weighted', zero_division=0)
            f1 = f1_score(y_test, y_pred, average='weighted', zero_division=0)
            
            self.results[name] = {
                'model': model,
                'accuracy': accuracy,
                'precision': precision,
                'recall': recall,
                'f1_score': f1,
                'train_time': train_time,
                'predict_time': predict_time,
                'predictions': y_pred
            }
            
            print(f"  ✓ Accuracy: {accuracy*100:.2f}% | Time: {train_time:.2f}s\n")
        
        print("All models trained successfully!")
    
    def get_results_dataframe(self):
        """
        Get results as pandas DataFrame
        
        Returns:
            DataFrame with model comparison results
        """
        data = []
        for name, results in self.results.items():
            data.append({
                'Model': name,
                'Accuracy': results['accuracy'] * 100,
                'Precision': results['precision'] * 100,
                'Recall': results['recall'] * 100,
                'F1-Score': results['f1_score'] * 100,
                'Train Time (s)': results['train_time'],
                'Predict Time (s)': results['predict_time']
            })
        
        df = pd.DataFrame(data)
        df = df.sort_values('Accuracy', ascending=False)
        return df
    
    def plot_comparison(self, save_path=None):
        """
        Plot model comparison
        
        Author: Molla Samser
        Company: RSK World
        Website: https://rskworld.in
        """
        df = self.get_results_dataframe()
        
        fig, axes = plt.subplots(2, 2, figsize=(15, 10))
        fig.suptitle('Music Genre Classification - Model Comparison\nRSK World - Molla Samser', 
                     fontsize=14, fontweight='bold')
        
        # Accuracy comparison
        axes[0, 0].barh(df['Model'], df['Accuracy'], color='steelblue')
        axes[0, 0].set_xlabel('Accuracy (%)')
        axes[0, 0].set_title('Model Accuracy Comparison')
        axes[0, 0].grid(axis='x', alpha=0.3)
        
        # Metrics comparison
        metrics = ['Accuracy', 'Precision', 'Recall', 'F1-Score']
        x = np.arange(len(df))
        width = 0.2
        
        for i, metric in enumerate(metrics):
            axes[0, 1].bar(x + i*width, df[metric], width, label=metric)
        
        axes[0, 1].set_xlabel('Models')
        axes[0, 1].set_ylabel('Score (%)')
        axes[0, 1].set_title('Performance Metrics Comparison')
        axes[0, 1].set_xticks(x + width * 1.5)
        axes[0, 1].set_xticklabels(df['Model'], rotation=45, ha='right')
        axes[0, 1].legend()
        axes[0, 1].grid(axis='y', alpha=0.3)
        
        # Training time comparison
        axes[1, 0].barh(df['Model'], df['Train Time (s)'], color='coral')
        axes[1, 0].set_xlabel('Training Time (seconds)')
        axes[1, 0].set_title('Training Time Comparison')
        axes[1, 0].grid(axis='x', alpha=0.3)
        
        # Accuracy vs Time scatter
        axes[1, 1].scatter(df['Train Time (s)'], df['Accuracy'], 
                          s=100, c='green', alpha=0.6, edgecolors='black')
        for idx, row in df.iterrows():
            axes[1, 1].annotate(row['Model'], 
                               (row['Train Time (s)'], row['Accuracy']),
                               fontsize=8, ha='right')
        axes[1, 1].set_xlabel('Training Time (seconds)')
        axes[1, 1].set_ylabel('Accuracy (%)')
        axes[1, 1].set_title('Accuracy vs Training Time')
        axes[1, 1].grid(alpha=0.3)
        
        plt.tight_layout()
        
        if save_path:
            plt.savefig(save_path, dpi=300, bbox_inches='tight')
            print(f"\nPlot saved to {save_path}")
        
        plt.show()
    
    def print_results(self):
        """Print detailed results"""
        df = self.get_results_dataframe()
        
        print("\n" + "="*70)
        print("Model Comparison Results")
        print("="*70)
        print(df.to_string(index=False))
        print("="*70)
        
        best_model = df.iloc[0]['Model']
        best_accuracy = df.iloc[0]['Accuracy']
        
        print(f"\n🏆 Best Model: {best_model}")
        print(f"   Accuracy: {best_accuracy:.2f}%")
        
        print("\n© 2026 RSK World - Molla Samser")
        print("Website: https://rskworld.in")
    
    def get_best_model(self):
        """Get the best performing model"""
        best_name = max(self.results, key=lambda x: self.results[x]['accuracy'])
        return best_name, self.results[best_name]['model']


# Example usage
if __name__ == "__main__":
    """
    Demo script for ModelComparator
    
    Author: Molla Samser
    Company: RSK World
    Website: https://rskworld.in
    """
    print("Model Comparison Utility")
    print("Author: Molla Samser | RSK World")
    print("Website: https://rskworld.in")
    print("\nThis utility compares multiple ML models:")
    print("- Random Forest")
    print("- Gradient Boosting")
    print("- SVM (RBF & Linear)")
    print("- K-Nearest Neighbors")
    print("- Decision Tree")
    print("- Naive Bayes")
    print("- Logistic Regression")
    
    print("\n© 2026 RSK World - Molla Samser")

251 lines•8.8 KB
python

About RSK World

Founded by Molla Samser, with Designer & Tester Rima Khatun, RSK World is your one-stop destination for free programming resources, source code, and development tools.

Founder: Molla Samser
Designer & Tester: Rima Khatun

Development

  • Game Development
  • Web Development
  • Mobile Development
  • AI Development
  • Development Tools

Legal

  • Terms & Conditions
  • Privacy Policy
  • Disclaimer

Contact Info

Nutanhat, Mongolkote
Purba Burdwan, West Bengal
India, 713147

+91 93305 39277

hello@rskworld.in
support@rskworld.in

© 2026 RSK World. All rights reserved.

Content used for educational purposes only. View Disclaimer