TechCrunch is heading to Tokyo — and bringing the Startup Battlefield with it
Back to Tutorials
aiTutorialintermediate

TechCrunch is heading to Tokyo — and bringing the Startup Battlefield with it

April 10, 20261 views5 min read

Learn to build an AI-powered music recommendation system using Spotify's audio features and machine learning algorithms. This intermediate tutorial teaches you how to create personalized track recommendations based on audio characteristics.

Introduction

In the wake of TechCrunch's expansion to Tokyo and the focus on AI, Robotics, Resilience, and Entertainment at SusHi Tech 2026, this tutorial will guide you through creating an AI-powered music recommendation system that could potentially be part of the future of the music industry. This project combines machine learning with music data to build a recommendation engine that analyzes user preferences and suggests similar tracks.

Prerequisites

  • Basic Python programming knowledge
  • Understanding of machine learning concepts
  • Installed libraries: scikit-learn, pandas, numpy, spotipy (for Spotify API access)
  • Spotify Developer account with API credentials
  • Basic understanding of audio features and music metadata

This tutorial will teach you how to build a recommendation system that leverages audio features from Spotify tracks to suggest similar music to users. The system will use collaborative filtering techniques combined with content-based filtering to provide personalized recommendations.

Step 1: Setting Up Your Development Environment

Install Required Libraries

First, ensure you have all necessary dependencies installed:

pip install scikit-learn pandas numpy spotipy

This step installs the core libraries needed for data manipulation, machine learning, and Spotify API integration. We'll use scikit-learn for our recommendation algorithms, pandas for data handling, and spotipy to access Spotify's extensive music database.

Create Spotify API Credentials

Visit Spotify Developer Dashboard and create a new app to get your Client ID and Client Secret. These credentials will allow your application to access Spotify's API and retrieve track information.

Step 2: Connecting to Spotify API

Initialize Spotify Client

import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

# Initialize Spotify client
client_credentials_manager = SpotifyClientCredentials(client_id='YOUR_CLIENT_ID',
                                                      client_secret='YOUR_CLIENT_SECRET')
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)

This code establishes a connection to Spotify's API using your credentials. The client credentials manager handles authentication, allowing you to access Spotify's vast music database without requiring user login.

Fetch Sample Music Data

def get_track_features(track_id):
    features = sp.audio_features(track_id)[0]
    return {
        'danceability': features['danceability'],
        'energy': features['energy'],
        'key': features['key'],
        'loudness': features['loudness'],
        'mode': features['mode'],
        'speechiness': features['speechiness'],
        'acousticness': features['acousticness'],
        'instrumentalness': features['instrumentalness'],
        'liveness': features['liveness'],
        'valence': features['valence'],
        'tempo': features['tempo']
    }

# Example usage
track_features = get_track_features('4cOdK2wGLETKB2e3031Q7K')

This function retrieves audio features from Spotify for a given track ID. Audio features like danceability, energy, and tempo provide quantitative measures that can be used to compare tracks and find similar ones.

Step 3: Building the Recommendation Engine

Create Feature Matrix

import pandas as pd
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity

# Sample data - in practice, you'd fetch this from Spotify
sample_tracks = [
    {'id': '4cOdK2wGLETKB2e3031Q7K', 'name': 'Blinding Lights', 'artist': 'The Weeknd'},
    {'id': '1lHC7K8230481234567890', 'name': 'Save Your Tears', 'artist': 'The Weeknd'},
    {'id': '2lHC7K8230481234567891', 'name': 'Levitating', 'artist': 'Dua Lipa'},
]

# Get features for all tracks
track_data = []
for track in sample_tracks:
    features = get_track_features(track['id'])
    features['track_id'] = track['id']
    features['track_name'] = track['name']
    track_data.append(features)

# Create DataFrame
df = pd.DataFrame(track_data)
print(df.head())

This step creates a structured dataset of track features that can be used for machine learning. The DataFrame will serve as our feature matrix, where each row represents a track and each column represents an audio feature.

Implement Similarity Calculation

# Select only numeric features for similarity calculation
numeric_features = ['danceability', 'energy', 'key', 'loudness', 'mode',
                   'speechiness', 'acousticness', 'instrumentalness',
                   'liveness', 'valence', 'tempo']

# Prepare feature matrix
X = df[numeric_features]

# Calculate cosine similarity between tracks
similarity_matrix = cosine_similarity(X)
print(similarity_matrix)

Cosine similarity is used to measure the angle between feature vectors of different tracks. Tracks with similar audio characteristics will have higher similarity scores, making this an effective method for finding similar music.

Step 4: Creating Recommendation Function

Build Recommendation System

def get_recommendations(track_id, similarity_matrix, df, top_n=5):
    # Find the index of the track
    track_index = df[df['track_id'] == track_id].index[0]
    
    # Get similarity scores for the track
    similarity_scores = list(enumerate(similarity_matrix[track_index]))
    
    # Sort by similarity score (descending)
    similarity_scores = sorted(similarity_scores, key=lambda x: x[1], reverse=True)
    
    # Get top N similar tracks (excluding the track itself)
    similar_tracks = similarity_scores[1:top_n+1]
    
    # Return track names and IDs
    recommendations = []
    for idx, score in similar_tracks:
        recommendations.append({
            'track_name': df.iloc[idx]['track_name'],
            'track_id': df.iloc[idx]['track_id'],
            'similarity_score': score
        })
    
    return recommendations

# Example usage
recommendations = get_recommendations('4cOdK2wGLETKB2e3031Q7K', similarity_matrix, df)
for rec in recommendations:
    print(f"{rec['track_name']} (Score: {rec['similarity_score']:.3f})")

This function takes a track ID and returns the most similar tracks based on audio features. It uses the pre-calculated similarity matrix to quickly find matches without recalculating all similarities each time.

Step 5: Testing Your Recommendation System

Run Sample Recommendations

# Test with a few different tracks
test_tracks = ['4cOdK2wGLETKB2e3031Q7K', '1lHC7K8230481234567890']

for track_id in test_tracks:
    print(f"\nRecommendations for track ID: {track_id}")
    recs = get_recommendations(track_id, similarity_matrix, df)
    for rec in recs:
        print(f"  - {rec['track_name']} (Similarity: {rec['similarity_score']:.3f})")

This testing phase validates that your recommendation system works correctly. You should see tracks that share similar audio characteristics being recommended together.

Summary

In this tutorial, you've built an AI-powered music recommendation system that leverages Spotify's audio features to suggest similar tracks. The system combines data from Spotify's API with machine learning techniques to create personalized music recommendations.

Key concepts covered:

  • Spotify API integration for accessing music data
  • Audio feature extraction and analysis
  • Cosine similarity for measuring track similarity
  • Content-based recommendation algorithms

This foundation could be expanded to include collaborative filtering, user ratings, and more sophisticated machine learning models. As the music industry evolves with AI integration, systems like this will become increasingly important for personalized music discovery and streaming services.

Related Articles