-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel_predict.py
More file actions
75 lines (60 loc) · 1.94 KB
/
Copy pathmodel_predict.py
File metadata and controls
75 lines (60 loc) · 1.94 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
# %%
import os
import pickle
import pandas as pd
import numpy as np
from tqdm import tqdm
from scipy.io import wavfile
from python_speech_features import mfcc
from keras.models import load_model
import pandas as pd
from sklearn.metrics import accuracy_score
# %%
def build_predictions(audio_dir):
y_true = []
y_pred = []
fn_prob = {}
print("Extracting features from audio")
for fn in tqdm(os.listdir(audio_dir)):
rate, signal = wavfile.read(os.path.join(audio_dir, fn))
label = fn2class[fn]
c = classes.index(label)
y_prob = []
for i in range(0, signal.shape[0] - config.step, config.step):
sample = signal[i:i+config.step]
x = mfcc(sample, rate, numcep=config.nfeat, nfilt=config.nfilt, nfft=config.nfft)
x = (x - config.min) / (config.max - config.min)
if config.mode == 'conv':
x = x.reshape(1, x.shape[0], x.shape[1], 1)
elif config.mode == 'time':
x = np.expand_dims(x, axis=0)
y_hat = model.predict(x)
y_prob.append(y_hat)
y_pred.append(np.argmax(y_hat))
y_true.append(c)
fn_prob[fn] = np.mean(y_prob, axis=0).flatten()
return y_true, y_pred, fn_prob
# %%
df = pd.read_csv('./sounds.csv')
classes = list(np.unique(df['class']))
fn2class = dict(zip(df.filename, df['class']))
p_path = os.path.join('pickles', 'conv.p')
# %%
with open(p_path, 'rb') as handle:
config = pickle.load(handle)
# %%
model = load_model(config.model_path)
y_true, y_pred, fn_prob = build_predictions('clean')
acc_score = accuracy_score(y_true=y_true, y_pred=y_pred)
# %%
y_probs = []
for i, row in df.iterrows():
y_prob = fn_prob[row.filename]
y_probs.append(y_prob)
for c, p in zip(classes, y_prob):
df.at[i, c] = p
# %%
y_pred = [classes[np.argmax(y)] for y in y_probs]
df['y_pred'] = y_pred
# %%
df.to_csv('prediction.csv', index=False)