-
Notifications
You must be signed in to change notification settings - Fork 0
/
librosa_speech_model.py
101 lines (71 loc) · 3.44 KB
/
librosa_speech_model.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
# -*- coding: utf-8 -*-
"""Librosa Speech Model.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/16NlLD6am6lyH5aDk4BmE5uJBH95oUdWX
"""
import librosa
import pandas as pd
import numpy as np
import os
audio_files = pd.DataFrame(pd.read_excel("data.xlsx")) # audio
audio_files
def preprocess_data(file_path):
audio, sr = librosa.load(file_path, sr=16000) #16000 is recommended sample rate for
mfccs_scaled = np.mean(librosa.feature.mfcc(y=audio, sr = 16000, n_mfcc=1000).T, axis=0)
return mfccs_scaled
import tensorflow as tf
mfcc_features_list = [] # list of spectrograms
for file_name in audio_files["file_name"]:
print(file_name)
audio = preprocess_data("audio_clips/" + file_name)
mfcc_features_list.append(audio) # append spectrogram audio data to audios. After the loop, audios will have the audio information of all the files as a spectrograms in different rows
audio_files.insert(0, "mfccs", mfcc_features_list) # inserting new audio column to audio_files
audio_files.head() # check what audio_files looks like
import seaborn
from scipy import stats
quality = "clairity" # THIS IS WHERE TO CHOOSE WHICH QUALITY WE WANT TO TRAIN THE MODEL ON
seaborn.histplot(data=audio_files[quality])
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(audio_files['mfccs'], audio_files[quality], test_size=0.25, random_state=48) # split into 80% 20% training testing datasets
y_train
from tensorflow.python.framework import ops
# convert training and testing data lists into np array
x_train = np.asarray(x_train)
x_test = np.asarray(x_test)
y_train = np.asarray(y_train)
y_test = np.asarray(y_test)
# convert to tensor
x_train = np.array([tensor for tensor in x_train])
x_test = np.array([tensor for tensor in x_test])
x_train
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten, Conv1D, MaxPooling1D
# create model
model = Sequential()
model.add(Dense(19, activation='relu'))
model.add(Dense(15, activation='relu'))
model.add(Dense(1, activation='relu'))
model.compile(loss='mse', optimizer='adam', metrics=['mae', 'mse'])
# train the model
history = model.fit(x_train, y_train, epochs = 120, validation_data=[x_test, y_test])
y_pred = model.predict(x_test)
from sklearn.metrics import r2_score
print(r2_score(y_test, y_pred))
for y in range(0, len(y_pred)):
print("Actual Enthusiasm", y_test[y], "Predicted enthusiasm:", y_pred[y][0])
from scipy.stats import spearmanr
coef, p = spearmanr(y_test, y_pred)
print(coef)
os.system("mkdir saved_models")
model.save("saved_models/" + quality + '.keras') # create ability to save model for any quality
os.system('zip -r "saved_models.zip" "saved_models"')
# after saving all different models...
def test_speech(file_name, characteristic):
if characteristic not in ("assertiveness", "enthusiasm", "clarity", "engagement"):
print("Error: test_speech called with bad characteristic. Please use one of the following: assertiveness, enthusiasm, clarity, engagement")
return -1
model = tf.keras.models.load_model('saved_models/' + quality + '.keras') # load in saved model
spectrogram = get_spectrogram("/content/gdrive/MyDrive/222 proj/audio_clips/" + file_name)
spectrogram = spectrogram[0:15000] # cut to 30 seconds
return model.predict(spectrogram) # return prediction