Created
March 8, 2020 15:02
-
-
Save yuyyuyu/1531b16513e6edff2f6be30228527a7b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from scipy.io import wavfile | |
import pandas as pd | |
import matplotlib.pyplot as plt | |
import numpy as np | |
from keras.layers import Conv2D, MaxPool2D, Flatten, LSTM | |
from keras.layers import Dropout, Dense, TimeDistributed | |
from keras.models import load_model | |
from keras.utils import to_categorical | |
from sklearn.utils.class_weight import compute_class_weight | |
from tqdm import tqdm | |
from python_speech_features import mfcc | |
import datetime | |
import pickle | |
from keras.callbacks import ModelCheckpoint | |
import pandas as pd | |
import sys | |
import keras | |
from sklearn.metrics import accuracy_score | |
print(sys.version) | |
print(keras.__version__) | |
def build_predictions(audio_directory): | |
y_true=[] | |
y_pred=[] | |
fn_prob={} | |
print('Extracting') | |
for fn in tqdm(os.listdir(audio_directory)): | |
rate,wav=wavfile.read(os.path.join(audio_directory,fn)) | |
label=fn2class[fn] | |
c=classes.index(label) | |
y_prob=[] | |
for i in range(0,wav.shape[0]-config.step,config.step): | |
sample=wav[i:i+config.step] | |
X=mfcc(sample,rate,numcep=config.nfeat,nfilt=config.nfilt,nfft=config.nfft).T | |
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('instruments2.csv') | |
classes=list(np.unique(df.label)) | |
fn2class=dict(zip(df.fname,df.label)) | |
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.fname] | |
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment