Skip to content

snehashish090/GenreDetect

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Music Genre Classification using SVM

This project implements a machine learning model to classify music into one of ten genres based on audio features. It uses a Support Vector Classifier (SVC) trained on the GTZAN dataset and includes functionalities for initial training, retraining with new data, and predicting the genre of a single audio file.

🎵 Features

  • Rich Feature Extraction: Extracts a comprehensive set of 258 features from audio files, including:
    • 40 MFCCs (Mean & Variance)
    • Delta & Delta-Delta MFCCs (Mean & Variance)
    • Chroma Features (Mean & Variance)
    • Spectral Centroid, Bandwidth, and Rolloff (Mean & Variance)
    • Zero-Crossing Rate (Mean & Variance)
    • RMS Energy (Mean & Variance)
  • Support Vector Machine (SVM): Utilizes a Support Vector Classifier (SVC) with an RBF kernel for robust classification.
  • Hyperparameter Tuning: Employs GridSearchCV to find the optimal C and gamma parameters for the SVC model, maximizing accuracy.
  • Scalability: Includes a dedicated function to retrain the model by incorporating new audio data with the existing dataset.
  • Persistence: Saves the trained model (.joblib) and feature scaler (.joblib) for easy reuse and prediction.

💿 Dataset

The model is trained on the GTZAN Genre Collection dataset. This dataset is famous for music genre recognition tasks.

  • Genres: blues, classical, country, disco, hiphop, jazz, metal, pop, reggae, rock.
  • Content: It consists of 1000 audio tracks, with 100 tracks for each of the 10 genres.
  • Format: Each audio file is a 30-second clip in .au format.

To use this project, you must download the dataset and organize it into a genres directory as follows:

.
├── genres/
│   ├── blues/
│   │   ├── blues.00000.au
│   │   └── ...
│   ├── classical/
│   │   └── ...
│   └── ... (other genre folders)
└── music_classifier.py

⚙️ Installation

  1. Clone the repository:

    git clone [https://your-repository-url.git](https://your-repository-url.git)
    cd your-repository-folder
  2. Create a virtual environment (recommended):

    python -m venv venv
    source venv/bin/activate  # On Windows, use `venv\Scripts\activate`
  3. Install the required libraries: You will need to install ffmpeg first.

    • On macOS (using Homebrew): brew install ffmpeg
    • On Ubuntu/Debian: sudo apt-get install ffmpeg
    • On Windows: Download the binaries from the official website and add them to your system's PATH.

    Then, install the Python packages:

    pip install librosa numpy scikit-learn joblib

🚀 Usage

The script is divided into three main functionalities. You can use them by uncommenting the respective function calls at the end of the script.

1. Initial Model Training

This process extracts features from the entire GTZAN dataset, performs a train-test split, finds the best hyperparameters using GridSearchCV, and saves the final model and scaler.

# To run the initial training:
if __name__ == '__main__':
    t1 = time.time()
    training()
    t2 = time.time()
    print(f"\nTotal training and evaluation took: {t2-t1:.2f} seconds")

This will create two files:

  • music_genre_svc_model.joblib: The trained SVC model.
  • music_genre_scaler.joblib: The StandardScaler fitted on the training data.

2. Predicting a Single File's Genre

Once the model is trained, you can predict the genre of any audio file. Make sure the file path is correct.

# To predict the genre of a new song:
if __name__ == '__main__':
    prediction = load_and_predict('genres/blues/blues.00006.au')
    print(f"The predicted genre is: {prediction}")

    prediction_hiphop = load_and_predict('path/to/your/hiphop_song.wav')
    print(f"The predicted genre is: {prediction_hiphop}")

3. Retraining the Model with New Data

If you have new, labeled audio files, you can retrain and improve the existing model. The function combines the original dataset with your new data and re-runs the entire training process.

# To retrain the model with new data:
if __name__ == '__main__':
    # List of new audio files and their correct labels
    new_files = [
        ('path/to/your/new_rock_song.mp3', 'rock'),
        ('path/to/another/pop_track.wav', 'pop')
    ]
    retrain_model_with_new_data(new_files)

This will overwrite the existing .joblib files with the newly improved model and scaler.

📂 File Structure

your-project-folder/
│
├── genres/                  # Folder containing the GTZAN dataset
│   ├── blues/
│   ├── classical/
│   └── ...
│
├── music_classifier.py      # Main Python script with all functions
│
├── music_genre_svc_model.joblib  # Saved model file (generated after training)
│
└── music_genre_scaler.joblib   # Saved scaler file (generated after training)

🤖 Model Details

  • Classifier: sklearn.svm.SVC
  • Kernel: Radial Basis Function (rbf)
  • Hyperparameter Tuning: GridSearchCV is used to optimize the following parameters over 5-fold cross-validation:
    • C (Regularization parameter): [0.1, 1, 10, 100]
    • gamma (Kernel coefficient): [0.001, 0.01, 0.1, 1, 'scale', 'auto']

💡 Future Improvements

  • Data Augmentation: Create more training data by applying effects like time-stretching, pitch-shifting, or adding noise to the existing audio files.
  • Deep Learning Models: Implement a Convolutional Neural Network (CNN) or a Recurrent Neural Network (RNN) using spectrograms as input, which can often yield higher accuracy for audio classification.
  • Real-time Prediction: Build a user interface (e.g., with Streamlit or Flask) that allows users to upload an audio file or record audio in real-time for genre prediction.
  • Optimize Feature Extraction: Experiment with other audio features or use feature selection techniques to identify the most impactful features.

About

A machine learning model to classify music genres

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages