The Wayback Machine - https://web.archive.org/web/20240903033749/https://www.geeksforgeeks.org/music-recommendation-system-using-machine-learning/
Open In App

Music Recommendation System Using Machine Learning

Last Updated : 01 Nov, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

When did we see a video on youtube let’s say it was funny then the next time you open your youtube app you get recommendations of some funny videos in your feed ever thought about how? This is nothing but an application of Machine Learning using which recommender systems are built to provide personalized experience and increase customer engagement.

In this article, we will try to build a very basic recommender system that can recommend songs based on which songs you hear.

Importing Libraries & Dataset

Python libraries make it very easy for us to handle the data and perform typical and complex tasks with a single line of code.

  • Pandas – This library helps to load the data frame in a 2D array format and has multiple functions to perform analysis tasks in one go.
  • Numpy – Numpy arrays are very fast and can perform large computations in a very short time.
  • Matplotlib/Seaborn – This library is used to draw visualizations.
  • Sklearn – This module contains multiple libraries having pre-implemented functions to perform tasks from data preprocessing to model development and evaluation.

Python3

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sb
 
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.manifold import TSNE
 
import warnings
warnings.filterwarnings('ignore')

                    

The dataset we are going to use contains data about songs released in the span of around 100 years. Along with some general information about songs some scientific measures of sound are also provided like loudness, acoustics, speechiness, and so on.

Python3

tracks = pd.read_csv('tracks_records.csv')
tracks.head()

                    

Output:

First five rows of the dataset

First five rows of the dataset

Data Cleaning

Data Cleaning is one of the important steps without which data will be of no use because the raw data contains a lot of noises that must be removed else the observations made from it will be inaccurate and if we are building a model upon it then it’s performance will be poor as well. Steps included in the data cleaning are outlier removal, null value imputation, and fixing the skewness of the data.

Python3

tracks.shape

                    

Output:

(586672, 19)

Python3

tracks.info()

                    

Output:

Basic information about the columns of dataset

Basic information about the columns of the dataset

Now. let’s check if there are null values in the columns of our data frame.

Python3

tracks.isnull().sum()

                    

Output:

Number of null values in each column

Number of null values in each column

The genre of music is a very important indicator of the type of music which is why we will remove such rows with null values. We could have imputed then as well but we have a huge dataset of around  6 lakh rows so, removing 50,000 won’t affect much (depending upon the case).

Python3

tracks.dropna(inplace = True)
tracks.isnull().sum().plot.bar()
plt.show()

                    

Output:

After removing rows containing null values

After removing rows containing null values

Now let’s remove some columns which we won’t be using to build our recommender system.

Python3

tracks = tracks.drop(['id', 'id_artists'], axis = 1)

                    

Exploratory Data Analysis

EDA is an approach to analyzing the data using visual techniques. It is used to discover trends, and patterns, or to check assumptions with the help of statistical summaries and graphical representations. 

The dataset we have contains around 14 numerical columns but we cannot visualize such high-dimensional data. But to solve this problem t-SNE comes to the rescue. t-SNE is an algorithm that can convert high dimensional data to low dimensions and uses some non-linear method to do so which is not a concern of this article.

Python3

model = TSNE(n_components = 2, random_state = 0)
tsne_data = model.fit_transform(a.head(500))
plt.figure(figsize = (7, 7))
plt.scatter(tsne_data[:,0], tsne_data[:,1])
plt.show()

                    

Output:

Scatter plot of the output of t-SNE

Scatter plot of the output of t-SNE

Here we can observe some clusters.

Formation of clusters in 2-D space

Formation of clusters in 2-D space

As we know multiple versions of the same song are released hence we need to remove the different versions of the same sone as we are building a content-based recommender system behind which the main worker is the cosine similarity function our system will recommend the versions of the same song if available and that is not what we want.

Python3

tracks['name'].nunique(), tracks.shape

                    

Output:

(408902, (536847, 17))

So, our concern was right so, let’s remove the duplicate rows based upon the song names.

Python3

tracks = tracks.sort_values(by=['popularity'], ascending=False)
tracks.drop_duplicates(subset=['name'], keep='first', inplace=True)

                    

Let’s visualize the number of songs released each year.

Python3

plt.figure(figsize = (10, 5))
sb.countplot(tracks['release_year'])
plt.axis('off')
plt.show()

                    

Output:

Countplot of the number of songs in subsequent years

Countplot of the number of songs in subsequent years 

Here we can see a boom in the music industry from the year 1900 to somewhere around 1990.

Python3

floats = []
for col in tracks.columns:
  if tracks[col].dtype == 'float':
    floats.append(col)
 
len(floats)

                    

Output:

10

There is a total of 10 such columns with float values in them. Let’s draw their distribution plot to get insights into the distribution of the data.

Python3

plt.subplots(figsize = (15, 5))
for i, col in enumerate(floats):
  plt.subplot(2, 5, i + 1)
  sb.distplot(tracks[col])
plt.tight_layout()
plt.show()

                    

Output:

Distribution plot of the continuous features

Distribution plot of the continuous features

Some of the features have normal distribution while some data distribution is skewed as well.

Python3

%%capture
song_vectorizer = CountVectorizer()
song_vectorizer.fit(tracks['genres'])

                    

As the dataset is too large computation cost/time will to too high so, we will show the implementation of the recommended system by using the most popular 10,000 songs.

Python3

tracks = tracks.sort_values(by=['popularity'], ascending=False).head(10000)

                    

Below is a helper function to get similarities for the input song with each song in the dataset.

Python3

def get_similarities(song_name, data):
   
  # Getting vector for the input song.
  text_array1 = song_vectorizer.transform(data[data['name']==song_name]['genres']).toarray()
  num_array1 = data[data['name']==song_name].select_dtypes(include=np.number).to_numpy()
   
  # We will store similarity for each row of the dataset.
  sim = []
  for idx, row in data.iterrows():
    name = row['name']
     
    # Getting vector for current song.
    text_array2 = song_vectorizer.transform(data[data['name']==name]['genres']).toarray()
    num_array2 = data[data['name']==name].select_dtypes(include=np.number).to_numpy()
 
    # Calculating similarities for text as well as numeric features
    text_sim = cosine_similarity(text_array1, text_array2)[0][0]
    num_sim = cosine_similarity(num_array1, num_array2)[0][0]
    sim.append(text_sim + num_sim)
     
  return sim

                    

To calculate the similarity between the two vectors we have used the concept of cosine similarity.

sim\left ( X, Y \right ) = \frac{X \cdot Y}{\left\| X\right\|\left\| Y\right\|}

Python3

def recommend_songs(song_name, data=tracks):
  # Base case
  if tracks[tracks['name'] == song_name].shape[0] == 0:
    print('This song is either not so popular or you\
    have entered invalid_name.\n Some songs you may like:\n')
     
    for song in data.sample(n=5)['name'].values:
      print(song)
    return
   
  data['similarity_factor'] = get_similarities(song_name, data)
 
  data.sort_values(by=['similarity_factor', 'popularity'],
                   ascending = [False, False],
                   inplace=True)
   
  # First song will be the input song itself as the similarity will be highest.
  display(data[['name', 'artists']][2:7])

                    

Now, it’s time to see the recommender system at work. Let’s see which songs are recommender system will recommend if he/she listens to the famous song ‘Shape of you’.

Python3

recommend_songs('Shape of You')

                    

Output:

Recommended songs if you hear 'Shape of you'

Recommended songs if you hear ‘Shape of you’

Let’s try this on one more song.

Python3

recommend_songs('Love Someone')

                    

Output:

Recommended songs if you hear 'Love Someone'

Recommended songs if you hear ‘Love Someone’

Below shown is the case if the song name entered is incorrect.

Python3

recommend_songs('Love me like you do')

                    

Output:

If the input song name is not in the dataset

If the input song name is not in the dataset

Conclusion

Although this model requires a lot of changes before it can be used in any real-world music app or website. But this is just an overview of how recommendation systems are built and used.



Previous Article
Next Article

Similar Reads

Machine Learning-based Recommendation Systems for E-learning
In today's digital age, e-learning platforms are transforming education by giving students unprecedented access to a wide range of courses and resources. Machine learning-based recommendation systems have emerged as critical tools for effectively navigating this vast amount of content. The article delves into the role of recommendation systems in e
9 min read
Ted Talks Recommendation System with Machine Learning
When did we see a video on youtube let's say it was funny then the next time you open your youtube app you get recommendations of some funny videos in your feed ever thought about how? This is nothing but an application of Machine Learning using which recommender systems are built to provide personalized experience and increase customer engagement.
5 min read
Music Genre Classifier using Machine Learning
Music is the art of arranging sound and noise together to create harmony, melody, rhythm, and expressive content. It is organized so that humans and sometimes other living organisms can express their current emotions with it. We all have our own playlist, which we listen to while traveling, studying, dancing, etc. In short, every emotion has a diff
5 min read
Crop Recommendation System using TensorFlow
In this tutorial, we will make a recommendation system that will take in the different environmental attributes such as the nitrogen, phosphorous, potassium content in the soil, temperature, etc., and predict what is the best crop that the user can plant so that it survives in the given climatic conditions. . Features Available in Crop Dataset The
8 min read
Recommendation System in Python
The ability to generate value for businesses by leveraging data and applying pertinent programming abilities is the fundamental component of both Data Science (DS) and Artificial Intelligence (AI). The way individuals can now access and enjoy products and services from the comfort of their homes with just a few clicks has been transformed by indust
15+ min read
Image Based Product Recommendation System
Recommender systems in online shopping help us deal with information overload by using both implicit and explicit user data, as well as internal system insights, to guide us towards the best product choices. Plus, these systems rely on detailed product catalogs and use images to turn potential buyers into loyal customers. Image-based recommendation
9 min read
Clustering Based Algorithms in Recommendation System
Recommendation systems have become an essential tool in various industries, from e-commerce to streaming services, helping users discover products, movies, music, and more. Clustering-based algorithms are a powerful technique used to enhance these systems by grouping similar users or items, enabling more personalized and accurate recommendations. T
5 min read
Rule Based System Vs Machine Learning System
There are two main approaches in Artificial intelligence they are rule-based systems and machine-learning systems. Rule-based systems follow explicit rules created by human experts. They're like a set of instructions given to a computer that follows to make decisions. These systems are good for problems with clear rules and paths. On the other hand
8 min read
Automated Machine Learning for Supervised Learning using R
Automated Machine Learning (AutoML) is an approach that aims to automate various stages of the machine learning process, making it easier for users with limited machine learning expertise to build high-performing models. AutoML is particularly useful in supervised learning, where you have labeled data and want to create models that can make predict
8 min read
Support vector machine in Machine Learning
In this article, we are going to discuss the support vector machine in machine learning. We will also cover the advantages and disadvantages and application for the same. Let's discuss them one by one. Support Vector Machines : Support vector machine is a supervised learning system and is used for classification and regression problems. Support vec
9 min read
Azure Virtual Machine for Machine Learning
Prerequisites: About Microsoft Azure, Cloud Based Services Some of the Machine Learning and Deep Learning algorithms may require high computation power which may not be supported by your local machine or laptop. In that case, creating a Virtual Machine on a cloud platform can provide you the expected computation power. We can have a system with hig
4 min read
Machine Learning Model with Teachable Machine
Teachable Machine is a web-based tool developed by Google that allows users to train their own machine learning models without any coding experience. It uses a web camera to gather images or videos, and then uses those images to train a machine learning model. The user can then use the model to classify new images or videos. The process of creating
7 min read
Artificial intelligence vs Machine Learning vs Deep Learning
Nowadays many misconceptions are there related to the words machine learning, deep learning, and artificial intelligence (AI), most people think all these things are the same whenever they hear the word AI, they directly relate that word to machine learning or vice versa, well yes, these things are related to each other but not the same. Let's see
4 min read
Need of Data Structures and Algorithms for Deep Learning and Machine Learning
Deep Learning is a field that is heavily based on Mathematics and you need to have a good understanding of Data Structures and Algorithms to solve the mathematical problems optimally. Data Structures and Algorithms can be used to determine how a problem is represented internally or how the actual storage pattern works & what is happening under
6 min read
Machine Learning - Learning VS Designing
In this article, we will learn about Learning and Designing and what are the main differences between them. In Machine learning, the term learning refers to any process by which a system improves performance by using experience and past data. It is kind of an iterative process and every time the system gets improved though one may not see a drastic
3 min read
Passive and Active learning in Machine Learning
Machine learning is a subfield of artificial intelligence that deals with the creation of algorithms that can learn and improve themselves without explicit programming. One of the most critical factors that contribute to the success of a machine learning model is the quality and quantity of data used to train it. Passive learning and active learnin
3 min read
Meta-Learning in Machine Learning
Traditional machine learning requires a huge dataset that is specific to a particular task and wishes to train a model for regression or classification purposes using these datasets. That’s radically far from how humans take advantage of their past experiences to learn quickly a new task from only a handset of examples. What is Meta Learning?Meta-l
13 min read
Continual Learning in Machine Learning
As we know Machine Learning (ML) is a subfield of artificial intelligence that specializes in growing algorithms that learn from statistics and make predictions or choices without being explicitly programmed. It has revolutionized many industries by permitting computer systems to understand styles, make tips, and perform tasks that were soon consid
10 min read
Few-shot learning in Machine Learning
What is a Few-shot learning?Few-shot learning is a type of meta-learning process. It is a process in which a model possesses the capability to autonomously acquire knowledge and improve its performance through self-learning. It is a process like teaching the model to recognize things or do tasks, but instead of overwhelming it with a lot of example
8 min read
What Is Meta-Learning in Machine Learning in R
In traditional machine learning, models are typically trained on a specific dataset for a specific task, and their performance is optimized for that particular task. However, in R Programming Language the focus is on building models that can leverage prior knowledge or experience to quickly adapt to new tasks with minimal additional training data.
7 min read
Types of Federated Learning in Machine Learning
Federated Learning is a powerful technique that allow a single machine to learn from many different source and converting the data into small pieces sending them to different Federated Learning (FL) is a decentralized of the machine learning paradigm that can enables to model training across various devices while preserving your data the data priva
5 min read
Understanding PAC Learning: Theoretical Foundations and Practical Applications in Machine Learning
In the vast landscape of machine learning, understanding how algorithms learn from data is crucial. Probably Approximately Correct (PAC) learning stands as a cornerstone theory, offering insights into the fundamental question of how much data is needed for learning algorithms to reliably generalize to unseen instances. PAC learning provides a theor
8 min read
One Shot Learning in Machine Learning
One-shot learning is a machine learning paradigm aiming to recognize objects or patterns from a limited number of training examples, often just a single instance. Traditional machine learning models typically require large amounts of labeled data for high performance. Still, one-shot learning seeks to overcome this limitation by enabling models to
7 min read
Difference Between Artificial Intelligence vs Machine Learning vs Deep Learning
Artificial Intelligence is basically the mechanism to incorporate human intelligence into machines through a set of rules(algorithm). AI is a combination of two words: "Artificial" meaning something made by humans or non-natural things and "Intelligence" meaning the ability to understand or think accordingly. Another definition could be that "AI is
14 min read
Difference Between Machine Learning and Deep Learning
If you are interested in building your career in the IT industry then you must have come across the term Data Science which is a booming field in terms of technologies and job availability as well. In this article, we will explore the Difference between Machine Learning and Deep Learning, two major fields within Data Science. Understanding these di
8 min read
Intrusion Detection System Using Machine Learning Algorithms
Problem Statement: The task is to build a network intrusion detector, a predictive model capable of distinguishing between bad connections, called intrusions or attacks, and good normal connections. Introduction: Intrusion Detection System is a software application to detect network intrusion using various machine learning algorithms.IDS monitors a
11 min read
Build a Recommendation Engine With Collaborative Filtering
Recommendation engines are responsible for enhancing user experience in every domain whether it's online shopping, social media, or movie streaming. With millions of content generated per second, it gets extremely difficult for businesses to recommend customers with content of their interest and behavior. This is where recommendation systems come i
7 min read
SVD in Recommendation Systems
Recommender systems have become a vital part of our digital lives, guiding us towards products, services, and content we might like. Among the various techniques used to power these systems, Singular Value Decomposition (SVD) and Matrix Factorization (MF) are prominent methods. This article explores the differences, applications, and effectiveness
3 min read
Movie and TV Show Recommendation Engine in R
A movie recommendation system, powered by machine learning recommendation engines, can create a personalized viewing experience that keeps viewers satisfied and engaged. Building a top-notch movie recommendation system is crucial because it directly impacts user retention and platform popularity. It's a complex mix of technology and creativity, wit
12 min read
What is a recommendation engine?
A recommendation engine is a system designed to suggest items or content to users based on their preferences, behaviors, or past interactions. These engines are used across a variety of platforms and industries, including e-commerce, media streaming, social networks, and more. The core goal of a recommendation engine is to personalize the user expe
4 min read
Practice Tags :