This repository has been archived by the owner on Jul 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Spotify Song Classifier using KNN.py
191 lines (94 loc) · 3.35 KB
/
Spotify Song Classifier using KNN.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
#!/usr/bin/env python
# coding: utf-8
# STEP 1: Access Spotify Credentials
# STEP 2: Download playlists music attribute data into csv
# STEP 3: Import needed libraries
# In[1]:
from sklearn.neighbors import NearestNeighbors
import pandas as pd
import plotly.express as px
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
import numpy as np
import seaborn as sns
# STEP 4: Read in csv file to each playlist and graph each attribute to spot differences. I am reading in my happy and euphonious playlists.
# In[3]:
happy = pd.read_csv("happy_all.csv")
euphon = pd.read_csv("euphonious_all.csv")
# below is an example of one of the attributes I graphed, you can do this for all attributes
# In[5]:
plt.plot(happy.energy, color='blue')
plt.plot(euphon.energy, color='red')
plt.xlabel("song #")
plt.ylabel("energy intensity")
plt.title("energy intensity across all songs in both playlists")
# STEP 5: Once you choose the attributes with the largest differences between the 2 playlists, combine both playlists datasets keeping wanted attributes then read in the new csv file
# In[7]:
happy_eupho = pd.read_csv("happy_eupho_new.csv")
happy_eupho.head()
# check for null values
# In[8]:
happy_eupho.isnull().values.any()
# check for integer datatypes (numpy arrays only work with integers)
# In[9]:
happy_eupho.dtypes
# In[10]:
happy_eupho['danceability']=happy_eupho['danceability'].astype(int)
# STEP 6: Normalize/Standardize the dataset
# In[11]:
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(happy_eupho.drop('target', axis=1))
# In[12]:
scaled_features = scaler.transform(happy_eupho.drop('target',axis=1))
scaled_features
# below is the pandas dataframe with the standardized values
# In[13]:
happy_eupho_feat = pd.DataFrame(scaled_features, columns = happy_eupho.columns[:-1])
happy_eupho_feat.head()
# STEP 7: Split dataset into training and testing sets
# In[15]:
from sklearn.model_selection import train_test_split
X = happy_eupho_feat
y = happy_eupho['target']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=30, shuffle=True)
# STEP 8: Train model
# find k value
# In[16]:
import math
math.sqrt(len(y_test))
# In[17]:
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=7,p=2,metric='euclidean')
knn.fit(X_train, y_train)
# STEP 9: Make predictions
# In[19]:
prediction = knn.predict(X_test)
prediction
# STEP 10: Evaluate Predictions using the Classification Report
# In[21]:
from sklearn.metrics import classification_report, confusion_matrix
print(classification_report(y_test, prediction))
# STEP 11: Evaluate alternative K-values for better predictions
#
# In[22]:
error_rate = []
for i in range(1,40):
knn = KNeighborsClassifier(n_neighbors=i)
knn.fit(X_train, y_train)
prediction_i = knn.predict(X_test)
error_rate.append(np.mean(prediction_i != y_test))
# Plot error rate
# In[24]:
plt.plot(error_rate, color='blue')
plt.title('error rate vs. k values')
plt.xlabel('k values')
plt.ylabel('error rate')
# STEP 11: Adjust K value according to the graph (lowest error rate)
# In[26]:
knn = KNeighborsClassifier(n_neighbors=27)
knn.fit(X_train, y_train)
prediction= knn.predict(X_test)
prediction
# In[27]:
print(classification_report(y_test, prediction))