Live demo: Open in Google Colab
An end-to-end Deep Learning system that composes novel, coherent polyphonic music using Long Short-Term Memory (LSTM) neural networks and Music21. Compatible with both local Windows environments and free Google Colab (T4 GPU).
- Project Overview
- System Architecture & Pipeline
- Curated Public-Domain Dataset
- Deep Learning Model Architecture
- Temperature-Based Probabilistic Sampling
- Project Structure
- Getting Started on Google Colab (Recommended)
- Getting Started Locally on Windows
- Automated Test Suite & Verification
- Sample Generated Outputs
- Author & Acknowledgments
Music composition possesses both temporal structure (rhythm and melody over time) and spatial structure (harmony and polyphonic chords). This project constructs a deep sequential recurrent model capable of:
- Extracting symbolic musical elements (notes, chords, quantized durations, and rests) from Standard MIDI Files (SMF).
- Learning sequential harmonic transitions using stacked LSTM layers with Embedding, Dropout, and Batch Normalization.
- Generating novel musical sequences using temperature-scaled stochastic sampling.
- Synthesizing generated tokens back into standard
.midfiles and playable.wavaudio.
+-----------------------+
| Raw MIDI Dataset | (Public Domain: Bach, Beethoven, Chopin, Mozart, Pachelbel)
+-----------+-----------+
|
v
+-----------------------+
| Music21 Preprocessor | -> Quantizes durations, extracts notes/chords/rests
+-----------+-----------+ Encodes into tokens (e.g. 'C4_0.5', 'C4.E4.G4_1.0')
|
v
+-----------------------+
| Sliding Window (X,y) | -> Window length = 32, Token-to-Index vocabulary
+-----------+-----------+
|
v
+-----------------------+
| Stacked LSTM Model | -> Embedding(128) -> LSTM(256) -> Dropout(0.3) ->
+-----------+-----------+ BatchNorm -> LSTM(256) -> Dense(256) -> Softmax
|
v
+-----------------------+
| Temperature Sampler | -> P(i) = exp(z_i / T) / sum(exp(z_j / T))
+-----------+-----------+ Controlled creativity (T in [0.2, 1.2])
|
+---------------------------+
| |
v v
+-----------------------+ +-----------------------+
| Standard MIDI (.mid)| | Playable Audio (.wav) |
+-----------------------+ +-----------------------+
To guarantee legal, copyright-free usage, the repository includes curated classical compositions located in data/raw_midi/:
- J.S. Bach: Two-Part Invention No. 1 in C Major (BWV 772)
- FrΓ©dΓ©ric Chopin: Prelude in E Minor (Op. 28 No. 4)
- Ludwig van Beethoven: Symphony No. 9 "Ode to Joy" Piano Theme
- W.A. Mozart: 12 Variations on "Ah vous dirai-je, Maman" (KV 265)
- Johann Pachelbel: Canon in D Major Piano Progression
All pieces are strictly in the public domain under CC0 / Open Access music archives.
| Layer | Type | Specifications | Function |
|---|---|---|---|
| 1 | Input | (batch_size, 32) |
Receives integer token sequence |
| 2 | Embedding | input_dim=Vocab, output_dim=128 |
Maps discrete musical tokens into dense continuous harmonic space |
| 3 | LSTM 1 | 256 units, return_sequences=True |
Extracts high-level melodic contour |
| 4 | Dropout 1 | rate=0.3 |
Regularization against overfitting |
| 5 | BatchNormalization 1 | Channels axis | Stabilizes activations across training |
| 6 | LSTM 2 | 256 units, return_sequences=False |
Encodes long-term sequence dependencies |
| 7 | Dropout 2 | rate=0.3 |
Regularization |
| 8 | BatchNormalization 2 | Channels axis | Stabilizes activations |
| 9 | Dense Hidden | 256 units, activation='relu' |
Non-linear feature combination |
| 10 | Dropout 3 | rate=0.3 |
Regularization |
| 11 | Output Dense | units=Vocab, activation='softmax' |
Categorical probability distribution for next token |
Rather than simply choosing the most likely token (greedy argmax, which causes repetitive loops), the generator applies temperature scaling:
-
$T = 0.3$ (Conservative): Sharpens probability peaks. Highly predictable, tightly follows motif patterns. -
$T = 0.8$ (Recommended / Sweet Spot): Balanced creativity and harmonic coherence. -
$T = 1.2$ (Adventurous): Broadens probability distribution. More unexpected, jazz-like or experimental transitions.
CodeAlpha_MusicGenerationAI/
βββ data/
β βββ raw_midi/ # 5 curated public-domain classical pieces (.mid)
β βββ processed/ # Vocabulary mapping and preprocessed token sequences
βββ models/
β βββ lstm_music_model_best.keras # Checkpoint weights (saved during training)
βββ output/
β βββ generated_music.mid # Synthesized AI MIDI file
β βββ generated_music.wav # Playable WAV audio file
β βββ training_loss_curve.png # Training loss/accuracy convergence plot
βββ notebooks/
β βββ Music_Generation_AI_Colab.ipynb # Complete, beginner-friendly Colab notebook
βββ src/
β βββ __init__.py
β βββ config.py # Hyperparameters, sequence length, and paths
β βββ midi_dataset.py # Dataset discovery and download utilities
β βββ preprocess.py # Music21 tokenizer & sequence builder
β βββ model.py # Keras stacked LSTM architecture
β βββ train.py # Training pipeline with callbacks & resume support
β βββ generate.py # Temperature-based generation engine
β βββ postprocess.py # MIDI writer & acoustic WAV synthesizer
β βββ utils.py # Diagnostics, audio display, and helpers
βββ tests/
β βββ test_midi_io.py # Unit tests for MIDI parsing & writing
β βββ test_preprocessing.py # Unit tests for vocabulary and windowing
β βββ test_generation.py # Unit tests for temperature sampling
β βββ run_all_tests.py # Complete automated test runner
βββ requirements.txt # Dependency specifications
βββ .gitignore # Git exclusion rules
βββ README.md # Project documentation
Google Colab allows you to train the deep learning model on a free cloud GPU (NVIDIA T4) with zero local installation:
- Open Google Colab.
- Click Upload and upload
notebooks/Music_Generation_AI_Colab.ipynb. - Enable GPU acceleration:
Runtime β Change runtime type β Hardware accelerator β T4 GPU β Save.
- Click Runtime β Run all (or run each cell sequentially).
- The notebook will automatically:
- Install
music21andfluidsynth. - Extract notes and train the LSTM model.
- Generate an original song with temperature sampling.
- Provide an instant Download Button for the
.midfile and an interactive audio player for the.wavaudio.
- Install
- Python 3.10 to 3.12 installed on your machine.
- Standard Command Prompt or PowerShell.
pip install -r requirements.txtStep A: Preprocess the MIDI dataset
python -m src.preprocessStep B: Train the LSTM Model
python -m src.train --epochs 35 --batch-size 32Tip: If you interrupt training, running python -m src.train will automatically resume from the latest saved checkpoint.
Step C: Generate Original Music
python -m src.generate --temperature 0.8 --length 150Outputs are written to:
output/generated_music.midoutput/generated_music.wav
The project includes a comprehensive automated unit test suite covering:
- MIDI header format integrity (SMF
MThdandMTrkchunks). - Music21 tokenization and quantized duration preservation.
- Invertibility of vocabulary mappings (
$t = \text{idx_to_token}[\text{token_to_idx}[t]]$ ). - Sliding window dimensions and target label alignment.
- Mathematical correctness of temperature sampling across temperature regimes.
- End-to-end generation of valid
.midand.wavfiles.
To run the test suite:
python -m tests.run_all_testsResult:
=================================================================
Running Test Suite: CodeAlpha MusicGenerationAI
=================================================================
test_end_to_end_generation_flow ... ok
test_low_temperature_peaks_highest_probability ... ok
test_temperature_sampling_bounds ... ok
test_midi_header_validity ... ok
test_midi_parsing_and_token_extraction ... ok
test_raw_midi_files_exist ... ok
test_token_to_midi_creation ... ok
test_wav_synthesis ... ok
test_quantize_duration ... ok
test_sequence_preparation_dimensions ... ok
test_vocabulary_mapping_invertibility ... ok
----------------------------------------------------------------------
Ran 11 tests in 5.915s
OK
>> ALL UNIT TESTS PASSED SUCCESSFULLY! <<
Sample generated outputs from the model are stored in the output/ directory:
output/generated_music.mid: Standard MIDI file playable in Windows Media Player, VLC, GarageBand, FL Studio, or any DAW.output/generated_music.wav: Synthesized 44.1 kHz acoustic piano audio rendition.
- Intern: CodeAlpha AI Intern
- Organization: CodeAlpha
- Project: Internship Project 3 β Music Generation with AI
- Tools Used: Python, TensorFlow, Keras, Music21, PrettyMIDI, FluidSynth, Google Colab, Google Antigravity.