-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmusicgenreclassification.py
More file actions
121 lines (94 loc) · 3.16 KB
/
musicgenreclassification.py
File metadata and controls
121 lines (94 loc) · 3.16 KB
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
# -*- coding: utf-8 -*-
"""MusicGenreClassification.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/12MJ9RUqALnwJW7HBtqzugjTOPGwGTYD0
"""
from google.colab import drive
drive.mount('/content/gdrive/')
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import confusion_matrix
import librosa
from joblib import dump, load
import numpy as np
import os
import time
import pandas as pd
import sys
# global fileName = []
# # contains all the paths for each au
# def fileIntoList(genre):
# for i in os.walk("/content/gdrive/My Drive/genres/" + genre):
# root, dirs, files = i
# # creating path using os
# for name in files:
# fullpath = os.path.join(root, name)
# fileName.append(fullpath)
# Splitting training/testing
Data = []
Label = []
# 80 v 20
minsize = sys.maxsize
# print(i.size)
def trainTest(genre, label):
global minsize
fileNames = []
for i in os.walk("/content/gdrive/My Drive/genres/" + genre):
root, dirs, files = i
for name in files:
fullpath = os.path.join(root, name)
if genre in fullpath:
fileNames.append(fullpath)
count = 0
print("file name loaded", len(fileNames))
# print("file name counted", fileNames[count])
while (count < len(fileNames)):
y, sr = librosa.load(fileNames[count])
y = y.flatten('F')[:y.shape[0]]
mfccs = librosa.feature.mfcc(y, sr=sr)
mean_data = [np.mean(feature) for feature in mfccs]
Data.append(mean_data)
if (len(mean_data)) < minsize:
minsize = len(mean_data)
count += 1
Label.append(label)
# print("file name counted", fileNames[count])
for i in range(len(Data)):
y = Data[i]
if len(y) > minsize:
y = y[:minsize]
Data[i] = y
print(minsize)
#genreList = ["blues", "classical", "country", "disco", "hiphop", "jazz", "metal", "pop", "reggae", "rock"]
genreList = ["blues", "classical", "country", "disco", "hiphop", "jazz", "metal", "pop", "reggae", "rock"]
yVals = np.identity(len(genreList))
for i in range(len(genreList)):
genre = genreList[i]
label = yVals[i]
trainTest(genre, label)
x_train, x_test, y_train, y_test = train_test_split(Data, Label)
scaler = StandardScaler()
scaler.fit(x_train)
x_train_scaled = scaler.transform(x_train)
x_test_scaled = scaler.transform(x_test)
pca = PCA().fit(x_train_scaled)
grid_params = {
'n_neighbors': [1, 3, 7, 99],
'weights': ['uniform', 'distance'],
'metric': ['euclidean', 'manhattan']
}
model = GridSearchCV(KNeighborsClassifier(), grid_params, cv=5, n_jobs=-1)
model.fit(x_train_scaled, y_train)
print(f'Model Score: {model.score(x_test_scaled, y_test)}')
y, sr = librosa.load("/content/gdrive/My Drive/genres/alla-turca.au")
y = y.flatten('F')[:y.shape[0]]
mfccs = librosa.feature.mfcc(y, sr=sr)
mean_data = [np.mean(feature) for feature in mfccs]
model.predict([mean_data])
import pickle
with open("/content/gdrive/My Drive/genres/testModel", 'wb') as f:
pickle.dump(model, f)