This project classifies short music tracks into genres using deep learning. We work with the FMA small dataset, convert audio files into log-mel spectrograms, and train PyTorch models that treat those spectrograms as time-frequency representations of the music.
The goal was not only to make a model that returns a label. We wanted a pipeline that is reproducible, easy to inspect, and honest about what improved the results and what did not. The final code keeps the structure deliberately simple: one dataset file, one model file, one training script, and one evaluation script.
Given a 30-second audio track, predict one of the 8 top-level FMA small genres:
Electronic, Experimental, Folk, Hip-Hop, Instrumental, International, Pop, Rock
The main learning pipeline is:
audio file -> log-mel spectrogram -> neural network -> genre prediction
We compare several model families:
- a small baseline CNN;
- a stronger residual CNN with an MLP classifier head;
- a CRNN that combines CNN features with a recurrent layer over time;
- an RNN-only ablation;
- ImageNet ResNets adapted to spectrogram inputs;
- a log-mel segment setup with track-level voting.
.
|-- main.py # train, then evaluate in one command
|-- setup_env.py # optional environment and data setup helper
|-- requirements.txt # pip dependencies
|-- environment.yml # conda-style dependency file
|-- src/
| |-- augment.py # spectrogram crop, masking, and noise transforms
| |-- dataset.py # FMA dataset, caching, dataloaders, segment mode
| |-- evaluate.py # checkpoint evaluation and confusion matrix
| |-- model.py # all model definitions
| |-- train.py # training loop
| `-- utils.py # seed, JSON, device, and plotting helpers
|-- scripts/
| |-- inspect_fma.py # build data/fma_small_manifest.csv
| |-- analyze_dataset.py # dataset plots and summaries
| |-- compare_experiments.py
| |-- make_manifest_subset.py
| |-- run_experiment_grid.py
| |-- test_dataset.py
| `-- test_model.py
|-- results/ # all committed result artifacts
`-- test/ # classroom repository checks
Large local folders are intentionally ignored by Git:
data/
checkpoints/
.venv/
The dataset is several GB and trained checkpoints can also be large, so the repo contains code and result artifacts, but not the raw audio or model weights.
We use FMA small, the small split of the Free Music Archive dataset.
External links:
- FMA project: https://github.com/mdeff/fma
- Metadata archive: https://os.unil.cloud.switch.ch/fma/fma_metadata.zip
- FMA small audio archive: https://os.unil.cloud.switch.ch/fma/fma_small.zip
- Kaggle reference notebook used for comparison ideas: https://www.kaggle.com/code/dapy15/music-genre-classification
After downloading and extracting the data, the expected local structure is:
data/fma_metadata/
data/fma_small/
Build the manifest with:
python scripts/inspect_fma.pyThis creates:
data/fma_small_manifest.csv
The manifest records the track id, audio path, genre, and official split. On our local setup, the usable split was:
| Split | Tracks |
|---|---|
| training | 6,394 |
| validation | 800 |
| test | 800 |
The fastest setup is:
python -m venv .venvOn Windows:
.\.venv\Scripts\Activate.ps1On Linux/macOS:
source .venv/bin/activateInstall dependencies:
pip install -r requirements.txtThere is also a helper script that creates the virtual environment, installs requirements, downloads FMA small, extracts it, and builds the manifest:
python setup_env.pyTo set up only the Python environment and skip the dataset download:
python setup_env.py --skip-dataBefore training, check that the dataset and models behave as expected:
python scripts/test_dataset.py
python scripts/test_model.pytest_dataset.py checks normal full-track spectrogram loading and the newer segment mode. test_model.py builds each model and runs a forward pass.
All model definitions live in src/model.py. The training script selects them with --model.
| Model name | Description |
|---|---|
cnn |
Small baseline CNN. Useful as a simple reference. |
cnn_mlp |
Residual CNN with average and max pooling plus an MLP head. This was our strongest non-segment model. |
crnn |
CNN front end followed by a bidirectional GRU and attention pooling. |
rnn |
RNN-only ablation over log-mel time frames. |
resnet18 |
ImageNet ResNet18 adapted to one-channel spectrograms. |
resnet34 |
ImageNet ResNet34 adapted to one-channel spectrograms. |
resnet50 |
ImageNet ResNet50 adapted to one-channel spectrograms. |
The default input is a normalized log-mel spectrogram with shape:
(channels=1, mel_bins=128, time_frames)
Training is done with src.train. The same script is used for every architecture, and the main choice is the value passed to --model.
python -m src.train --model <model_name> --epochs <epochs> --batch-size <batch_size>The model name can be cnn, cnn_mlp, crnn, rnn, resnet18, resnet34, or resnet50. We used the smaller CNN as the baseline, then trained stronger models to compare whether more capacity, temporal modeling, or transfer learning helped.
The number of epochs controls how many full passes the model makes over the training split. Most final runs used 15 epochs because this was enough to compare models without wasting GPU time; longer runs can be useful, but validation accuracy should be watched for overfitting.
Batch size depends on the model and GPU memory. Simpler models can use larger batches, while CRNNs and ResNets may need smaller batches. --num-workers controls how many dataloader workers prepare batches in parallel; on the GPU server we usually used 4.
The crop and segment options control how much of each track the model sees. --crop-frames uses one fixed-width spectrogram window. --segment-frames and --segment-stride train on overlapping windows and are used for the segment-voting experiment.
Each run should use its own checkpoint and result folders, so the outputs do not overwrite each other. Training saves:
<checkpoint-dir>/best_model.pt
<results-dir>/training_history.json
<results-dir>/training_curves.png
The history JSON stores train/validation loss and accuracy for every epoch. The PNG shows the same values in a graph.
Example command for our best completed model:
python -m src.train --model cnn_mlp --epochs 15 --batch-size 64 --num-workers 4 --checkpoint-dir checkpoints/cnn_mlp --results-dir results/cnn_mlpEvaluate a checkpoint on the test split:
python -m src.evaluate --checkpoint checkpoints/cnn_mlp/best_model.pt --results-dir results/cnn_mlpEvaluation reconstructs the correct architecture from the checkpoint arguments, so the model name does not need to be repeated.
Evaluation saves:
<results-dir>/test_metrics.json
<results-dir>/classification_report.txt
<results-dir>/confusion_matrix.csv
<results-dir>/confusion_matrix.png
The metrics include accuracy, macro F1, weighted F1, per-class precision/recall, and the confusion matrix.
main.py builds the manifest if needed, trains, and then evaluates:
python main.py --model cnn_mlp --epochs 15 --batch-size 64 --num-workers 4Train only:
python main.py --model cnn_mlp --no-evalOne limitation of using a single crop per track is that a song may contain several different sections. A model can see an intro, a chorus, or a quiet instrumental passage and make a different prediction for each one.
To address this, the code supports overlapping log-mel segments. The dataset still caches one full spectrogram per track, but training indexes several windows inside it. During evaluation, the model predicts every segment and the probabilities are averaged to get one final prediction per track.
Train with 512-frame segments and 50 percent overlap:
python -m src.train --model cnn_mlp --segment-frames 512 --segment-stride 256 --epochs 20 --batch-size 64 --num-workers 4 --checkpoint-dir checkpoints/segments_cnn_mlp --results-dir results/segments_cnn_mlpEvaluate with track-level voting:
python -m src.evaluate --checkpoint checkpoints/segments_cnn_mlp/best_model.pt --batch-size 128 --num-workers 4 --results-dir results/segments_cnn_mlpFor a segmented checkpoint, voting is enabled automatically. To inspect raw segment-level performance instead:
python -m src.evaluate --checkpoint checkpoints/segments_cnn_mlp/best_model.pt --no-votingThe repo includes a small experiment-grid helper:
python scripts/run_experiment_grid.py --epochs 100 --batch-size 64 --num-workers 4It trains several simple variants:
- baseline settings;
- lower learning rate;
- lower dropout;
- stronger dropout plus weight decay;
- 25 percent training subset;
- 50 percent training subset.
Compare result folders:
python scripts/compare_experiments.pyCommitted grid artifacts are stored in results/grid_*.
The strongest completed runs were trained on the ETSE GPU VM using cached log-mel spectrograms and the official FMA split. Test accuracy is measured on the 800 held-out test tracks, with 100 tracks per genre. Because the test set is balanced, accuracy, macro F1, and weighted F1 are all useful, but macro F1 is still the clearest way to check whether the model is learning every genre instead of only doing well on the easier ones.
For the segmented models, the model sees several overlapping windows from each track. At evaluation time, each segment produces class probabilities and the probabilities are averaged to make one final track-level prediction. This is stricter than reporting segment-level accuracy because the final prediction is still one label per song.
Each committed result folder contains the files needed to inspect the run:
training_history.json # train/validation loss and accuracy per epoch
training_curves.png # plotted training curves
test_metrics.json # accuracy, F1 scores, and per-class metrics
classification_report.txt # readable precision/recall/F1 table
confusion_matrix.csv/png # genre confusion matrix
| Model | Best validation accuracy | Test accuracy | Macro F1 | Notes |
|---|---|---|---|---|
segment_crnn |
0.6290 | 0.5538 | 0.5457 | Best committed result; segment voting enabled. |
cnn_mlp |
0.6113 | 0.5500 | 0.5367 | Best non-segment model. |
crnn |
0.5725 | 0.5100 | 0.4958 | Temporal model without segment voting. |
segment_cnn |
0.5705 | 0.5025 | 0.4901 | Segment voting with the simple CNN. |
segment_resnet50 |
0.5550 | 0.5000 | 0.4909 | Segment voting with frozen ResNet50. |
segment_rnn |
0.5535 | 0.4638 | 0.4574 | Segment voting with RNN-only model. |
rnn |
0.5250 | 0.4537 | 0.4282 | RNN-only ablation. |
resnet50 |
0.4838 | 0.4462 | 0.4086 | Frozen ImageNet backbone. |
resnet34 |
0.5025 | 0.4150 | 0.4100 | Frozen ImageNet backbone. |
resnet18 |
0.4925 | 0.4100 | 0.3936 | Frozen ImageNet backbone. |
cnn |
0.4838 | 0.3700 | 0.3444 | Simple baseline. |
The best model was segment_crnn. It reached 55.38 percent test accuracy and 54.57 percent macro F1. The validation score was higher than the test score, so we do not treat the validation number as the final performance. The important result is the held-out test result.
The best non-segment model was cnn_mlp, with 55.00 percent test accuracy and 53.67 percent macro F1. This is very close to segment_crnn, which tells us that the residual CNN representation was already strong. Segment voting and temporal modeling gave a small extra improvement rather than a completely different level of performance.
The plain CNN baseline was much weaker at 37.00 percent test accuracy. That gave us a useful lower bound: the task is learnable from log-mel spectrograms, but the model needs enough capacity to represent rhythm, texture, and longer musical patterns.
For segment_crnn, evaluation used 4,000 segments for 800 tracks, so each test track contributed five overlapping segments. The raw segment accuracy was 53.88 percent, while track-level voting improved the final result to 55.38 percent. The gain is modest, but it supports the idea that listening to several parts of the song is better than judging the whole track from one crop.
| Genre | Precision | Recall | F1 | Observation |
|---|---|---|---|---|
| Electronic | 0.70 | 0.64 | 0.67 | Usually recognized well. |
| Experimental | 0.43 | 0.50 | 0.47 | Often overlaps with Instrumental and Folk. |
| Folk | 0.33 | 0.27 | 0.30 | Hardest class for the model. |
| Hip-Hop | 0.70 | 0.90 | 0.79 | Strongest class, with very high recall. |
| Instrumental | 0.50 | 0.47 | 0.48 | Often confused with Folk or Experimental. |
| International | 0.60 | 0.75 | 0.66 | Strong recall, usually separated well. |
| Pop | 0.44 | 0.39 | 0.41 | Often confused with Hip-Hop, Rock, or Electronic. |
| Rock | 0.69 | 0.51 | 0.59 | Good precision, but some Rock tracks are predicted as Pop. |
The confusion matrix shows that Hip-Hop is the clearest genre in this setup: 90 of the 100 Hip-Hop test tracks were classified correctly. International and Electronic were also relatively strong. Folk was the weakest genre, with many Folk tracks predicted as Experimental, International, Pop, or Rock. This is musically plausible because acoustic, vocal, and regional tracks can share features across those labels. Pop was also difficult because it borrows production styles from several other genres.
The committed grid result folders show a separate tuning pass. In that grid, the best committed result was:
| Experiment | Test accuracy | Macro F1 | Comment |
|---|---|---|---|
results/grid_train50_100 |
0.4475 | 0.4050 | Best committed grid artifact. |
results/grid_dropout02_100 |
0.4038 | 0.3796 | Lower dropout improved validation but not enough on test. |
results/grid_lr5e4_100 |
0.3750 | 0.3406 | Lower learning rate underperformed. |
results/grid_baseline_100 |
0.3675 | 0.3416 | Grid baseline. |
results/grid_dropout05_wd1e3_100 |
0.3650 | 0.3481 | Stronger regularization was not helpful. |
results/grid_train25_100 |
0.3262 | 0.2779 | Less data clearly hurt. |
The grid experiments were useful because they showed that small optimizer and regularization changes were less important than the representation and evaluation setup. The smaller-data runs also confirmed that the model benefits from more training examples. This matters for FMA small because every class has only around 1,000 tracks, so throwing away training data hurts quickly.
The model ablations were also informative. The RNN-only model learned something, but it stayed below the CNN-based models because it reads each time frame as a vector and has no local frequency-time feature extractor. The frozen ResNet models also underperformed the custom CNN models. ImageNet features are powerful for natural images, but spectrograms have different structure, and simply repeating the spectrogram channel into RGB does not make the pretrained filters ideal for music.
We also tested a Kaggle-inspired MFCC/segment preparation. It did not beat the log-mel pipeline on the honest FMA track split:
| Setup | Best test accuracy | Macro F1 | Main lesson |
|---|---|---|---|
| Best log-mel result | 0.5538 | 0.5457 | Best representation for our setup. |
MFCC-style cnn_mlp |
0.4938 | 0.4840 | Useful comparison, but weaker here. |
The Kaggle notebook was helpful as a reference, especially for thinking about audio preprocessing and segment-based classification. However, its reported accuracy should not be compared directly to our final number unless the data split and evaluation method are identical. A segment-level split can be much easier than a track-level split because segments from the same song may appear in both training and testing. Our evaluation uses the official FMA split and reports one prediction per held-out track, so it is a stricter test of generalization.
The final pipeline came from several rounds of trial and error:
- We first cleaned the template repository and built a simple reproducible pipeline around FMA small: manifest creation, log-mel spectrogram loading, caching, model training, and final test evaluation.
- The first baseline was a small CNN. It trained and gave us proof that the labels were learnable, but its test accuracy was too low, so we treated it mainly as a reference point.
- We then moved to a stronger residual CNN with average and max pooling plus an MLP head. This was the first model that clearly worked well, because convolutional layers are a good fit for local time-frequency patterns in spectrograms.
- We tried a CRNN to add explicit time modeling. The plain CRNN was useful but not clearly better than the residual CNN by itself, which suggested that temporal modeling alone was not enough.
- We added an RNN-only model as an ablation. It learned some genre structure, but it was weaker because it did not have a CNN front end to detect local spectrogram patterns.
- We tested frozen ImageNet ResNets adapted to spectrograms. They were not as strong as expected because natural-image pretraining does not transfer perfectly to one-channel audio spectrograms.
- We ran a small tuning grid with learning rate, dropout, weight decay, and smaller training subsets. The main lesson was that reducing training data hurt, while small optimizer changes did not solve the core problem.
- We compared against a Kaggle-inspired MFCC/segment preparation. It was useful as a reference, but on our official track-level split it did not beat the log-mel setup.
- The last improvement was segment training and track-level voting. This helped because a single 30-second track can contain different musical sections, and voting over several windows makes the final prediction less dependent on one crop.
This path is why the final project keeps both the simple cnn_mlp model and the stronger segment_crnn result. The cnn_mlp is easier to understand and already performs well, while segment_crnn adds the best final accuracy by combining temporal modeling with segment voting.
The best committed result is now segment_crnn. It only slightly beats cnn_mlp, but the improvement is meaningful because it combines two useful ideas: temporal modeling through the GRU and track-level voting across several log-mel segments. The cnn_mlp result is still important because it is the strongest simpler model and is easier to explain.
We look at both accuracy and macro F1 because standard accuracy can hide the classes the model struggles with. Macro F1 treats all genres equally, so it lets us see if the model is actually learning everything or just doing well on the easier ones. It helps to read the confusion matrices in the results folder alongside these scores.
Our grid experiments showed that adding more training data helped, but changing the learning rate or regularization did not make much of a difference. The segment experiments then added a small extra gain by letting the model vote over several parts of each song. This tells us that getting the input data, model structure, and evaluation strategy right was more important here than making minor optimizer adjustments.
Finally, the Kaggle-style MFCC experiment was helpful, even though it did not give us our highest scores. It showed that a setup that works well in a Kaggle notebook does not automatically carry over to our specific data split. For our data, log-mel spectrograms ended up working better.
The best gains came from the representation and the shape of the model, not from making everything bigger.
The cnn_mlp model worked very well because spectrogram genre cues are local in both frequency and time. A residual CNN can detect those local patterns, and the average-plus-max pooling keeps both broad and strong local evidence before the classifier head.
The CRNN became strongest once we combined it with segment voting. This makes sense for audio because music unfolds over time, and voting across segments reduces the risk of judging a whole track from one unrepresentative crop.
The RNN-only model was useful as a sanity check. It learned, but it was weaker than the CNN models because it sees each time frame as a vector and has no explicit local frequency-time feature extractor.
The frozen ResNets were less successful than expected. ImageNet pretraining is powerful, but natural images and spectrograms are different domains. Repeating a one-channel spectrogram into three channels lets a ResNet run, but it does not magically make ImageNet filters ideal for music.
The Kaggle-style MFCC experiment was informative. High scores in notebooks can come from a different split, segment-level evaluation, or a less strict setup. On our track-level split, log-mel spectrograms gave better results.
The final accuracy is reasonable for FMA small, but this is still a hard task. Many genres overlap musically, and a 30-second clip may contain sections that sound unlike the track's top-level label. The confusion matrix is therefore more important than accuracy alone: it shows which genres are being confused and whether the errors are musically plausible.
The main limitation is that the improvement from segment voting is still modest. It helps the model listen to several parts of the same song, but genre labels are still broad and sometimes ambiguous. A more systematic sweep over segment length, stride, and augmentation would be the next step.
Other improvements worth trying:
- fine-tune ResNet backbones instead of keeping them frozen;
- train
cnn_mlpandcrnnlonger with a careful learning-rate schedule; - ensemble
cnn_mlpandcrnnpredictions; - add audio-level augmentation before spectrogram extraction;
- inspect per-genre errors and tune the model around the weakest classes.
From a fresh clone:
python setup_env.py
python -m src.train --model crnn --segment-frames 512 --segment-stride 256 --epochs 20 --batch-size 32 --num-workers 4 --checkpoint-dir checkpoints/segment_crnn --results-dir results/segment_crnn
python -m src.evaluate --checkpoint checkpoints/segment_crnn/best_model.pt --batch-size 128 --num-workers 4 --results-dir results/segment_crnnOn a GPU server, activate the environment first and use the same commands. The first run may be slower because spectrograms are cached under data/cache_spectrograms/; later runs reuse those cached tensors.