{"cells":[{"metadata":{"id":"ofGTg5PtMwOn"},"cell_type":"markdown","source":"# **FREE SOUND AUDIO TAGGING**","execution_count":null},{"metadata":{"id":"NZhIRdktMvtA"},"cell_type":"markdown","source":"Freesound is a collaborative database of Creative Commons Licensed sounds. The aim of this competition is to classify audio files that cover real-world sounds from musical instruments, humans, animals, machines, etc. Few of the labels are: bark, bass_drum, bus,etc. One of the challenges is that not all labels are manually verified. A creative solution should be able to partially rely on these weak annotations.\n\n","execution_count":null},{"metadata":{"id":"cm9KSTurNjhO"},"cell_type":"markdown","source":"In this project we have tried to calculate MFCC of the audio files .","execution_count":null},{"metadata":{"id":"vrh9XTlaPuo8"},"cell_type":"markdown","source":"In sound processing, the mel-frequency cepstrum (MFC) is a representation of the short-term power spectrum of a sound, based on a linear cosine transform of a log power spectrum on a nonlinear mel scale of frequency.\n\nMel-frequency cepstral coefficients (MFCCs) are coefficients that collectively make up an MFC. They are derived from a type of cepstral representation of the audio clip (a nonlinear \"spectrum-of-a-spectrum\"). The difference between the cepstrum and the mel-frequency cepstrum is that in the MFC, the frequency bands are equally spaced on the mel scale, which approximates the human auditory system's response more closely than the linearly-spaced frequency bands used in the normal cepstrum. This frequency warping can allow for better representation of sound, for example, in audio compression.\n\nMFCCs are commonly derived as follows:\n\n\n1.   Take the Fourier transform of (a windowed excerpt of) a signal.\n\n2.   Map the powers of the spectrum obtained above onto the mel scale, using triangular overlapping windows.\n\n3.   Take the logs of the powers at each of the mel frequencies.\n\n4.   Take the discrete cosine transform of the list of mel log powers, as if it were a signal.\n\n5.   The MFCCs are the amplitudes of the resulting spectrum.\n\n\n\n\n","execution_count":null},{"metadata":{"id":"TKdO2TArQoYb","trusted":false},"cell_type":"code","source":"import os\nos.getcwd()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!apt update\n!apt-get install -y libsndfile1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install SoundFile\n","execution_count":null,"outputs":[]},{"metadata":{"id":"3HaH64gTlcgH","outputId":"1f24660b-1e05-4030-db9f-1bdf87fe42a2","trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport IPython.display as ipd\nimport IPython.display as ipd\nfrom scipy.fftpack import fft, fftfreq, fftshift\nfrom scipy.signal import find_peaks\nfrom scipy.fftpack import dct\nfrom scipy.io import wavfile\nfrom skimage import util\nimport scipy.signal as signal\nfrom pandas import read_csv\nimport seaborn as sns\nimport scipy\nimport pandas as pd\nimport numpy as np\nimport pylab\nimport librosa\nimport librosa.display\nimport wave\nimport struct\nimport sklearn\nplt.style.use('classic')\n%matplotlib inline\n# Set default font size\n#plt.rcParams['font.size'] = 20\n#pd.set_option('display.max_columns',60)\n#plt.style.available","execution_count":null,"outputs":[]},{"metadata":{"id":"xfLOsNS9lcgM","scrolled":true,"trusted":true},"cell_type":"code","source":"def printsig():\n    print('fs_rate:',fs_rate, 'Channels:', audio_chnl, 'duration:',duration,'sec.', 'Ts:', Ts, 'time:',time,'time_len:',time_len)\n    # Plot original Audio signal\n    plt.figure(figsize=(10, 3))\n    plt.plot(time, sig_o)\n    plt.title('Origin wave signal')\n    plt.ylabel('Amplitude')\n    plt.xlabel('Time')\n    plt.show() \n    plt.figure(figsize=(10, 3))\n    plt.plot(time, sig_s)\n    plt.title('windowed wave signal')\n    plt.ylabel('Amplitude')\n    plt.xlabel('Time')\n    plt.show() ","execution_count":null,"outputs":[]},{"metadata":{"id":"gtj_fsRulcgQ","trusted":true},"cell_type":"code","source":"def print_mfcc():\n    # Plot mfcc - the amplitude envelope of a waveform.\n    plt.figure(figsize=(10, 3)) \n    librosa.display.waveplot(mfcc, sr=fs_rate)\n    plt.title('mfcc envelope')\n    plt.ylabel('Envelope Amplitude')\n    plt.show()    \n    # Plot mfcc spectrum.\n    plt.figure(figsize=(10, 3))\n    plt.title('mfcc spectogram')\n    mfcc_spec=librosa.feature.mfcc(y=sig_s, sr=fs_rate)\n    mfcc_spec=sklearn.preprocessing.scale(mfcc_spec, axis=1)\n    librosa.display.specshow(mfcc_spec, sr=fs_rate, x_axis='time') \n    plt.show()     ","execution_count":null,"outputs":[]},{"metadata":{"id":"PIgC4u-slcgT","scrolled":false,"trusted":true},"cell_type":"code","source":"def print_fft(sigfft,sigfreqs):\n    # plot fft of signal\n    plt.figure(figsize=(10, 3))\n    plt.plot(sigfreqs,sigfft) \n    plt.title('FFT of signal')\n    plt.ylabel('Power')\n    plt.xlabel('Frequency')\n    plt.show() \n\n    plt.figure(figsize=(10, 3))\n    l=int(len(sigfft)/2)\n    plt.plot(sigfreqs[1:l],sigfft[1:l]) \n    plt.title('positive FFT of signal')\n    plt.ylabel('Power')\n    plt.xlabel('Frequency')\n    plt.show()  ","execution_count":null,"outputs":[]},{"metadata":{"id":"Wr7TRAH0lcgY","scrolled":false,"trusted":true},"cell_type":"code","source":"def print_spectogram():\n    frqs, times, xsig = signal.spectrogram(sig_s, fs_rate,  nperseg=1024,  # window='hamming',\n                                       noverlap = 1024-256,detrend=False, scaling='spectrum')\n    plt.figure(figsize=(10,5));\n    plt.pcolormesh(times, frqs/1000, 20*np.log10(xsig), cmap='viridis' ) #viridis  magma  \n    plt.title('Signal Spectrogram')\n    plt.xlabel('Time [sec]')\n    plt.ylabel('Frequency [kHz]');\n    plt.show()  ","execution_count":null,"outputs":[]},{"metadata":{"id":"SuBm9C6wlcgd","trusted":true},"cell_type":"code","source":"def find_N(N_len):\n    return 2**14 if N_len>=2**14 else N_len","execution_count":null,"outputs":[]},{"metadata":{"id":"ZdMfh4c_lcgh","scrolled":true,"trusted":true},"cell_type":"code","source":"def process_fft():\n    #entire signal \n    N=find_N(time_len)\n    #N=time_len\n    fftsig= np.fft.fft(sig,N)\n    sigfft=np.abs(fftsig)\n    sigfreqs = np.fft.fftfreq(N,Ts)\n\n    # slice signal to small frames\n    frame_len = 1024 # about 20msec\n    frame_time = Ts\n    frames = util.view_as_windows(sig, window_shape=(frame_len,), step=512) #step=128)\n    win = np.hanning(frame_len+1)[:-1]   # to try with hamming as well\n    frames = frames*win\n    frames = frames.T\n    num_of_frames=frames.shape[0]\n    #print(f'Signal shape: {sig.shape}, framed signal shape: {frames.shape[1]}')\n    spects= np.fft.fft(frames, n=frame_len, axis=0)\n    spects=np.abs(spects)\n    #max_pwr = spects.max()\n    frame_f = np.fft.fftfreq(frame_len,frame_time) #scipy.fftpack.fftfreq(frame_len,frame_time)\n    pos=int(frame_len/2)\n    max_val = np.amax(spects) # find fft max value    \n            \n    for x in range(frames.shape[1]):      \n        idxs = np.argmax(spects[:pos,x])   # index of max peak in frame :pos\n        if spects[idxs,x] > (0.5 * max_val): # 0.65\n            sig_freqs.append(frame_f[idxs])  # create a list of frequencies in each frame        \n\n#         if fname=='962ffc01.wav':#3315ec7f.wav 0006ae4e 6459fc05 \n#             print('column', x)\n#             print(f'maximum value in column {x} {np.amax(spects[:pos,x])}')\n#             print(f'the idxs {idxs} with the value  of {spects[idxs,x]}') \n    \n    # prints and plots a single wave file\n    if fname=='074a72f0.wav':  # 6459fc05 / 3315ec7f / 962ffc01.wav  / 54073d7e / d41f1ae5.wav\n        print('File: 074a72f0.wav, Labled: Bicycle bell ')  \n        printsig()\n        print_mfcc()\n        print_fft(sigfft,sigfreqs)\n        print_spectogram()\n        #print('max val',max_val)\n        print(f'sig_freqs: {sig_freqs}')\n        \n    static_feats=[np.mean(sig_freqs), np.median(sig_freqs),np.std(sig_freqs),np.var(sig_freqs),\n                  min(sig_freqs), max(sig_freqs)]\n\n    return static_feats","execution_count":null,"outputs":[]},{"metadata":{"id":"ef1Q0oUulcgl"},"cell_type":"markdown","source":"## 1.  Data  Collection ","execution_count":null},{"metadata":{"id":"GOskuv78lcgl","outputId":"c4413069-d140-4974-fe47-1e6d82f6b3b3","scrolled":true,"trusted":true},"cell_type":"code","source":"\nclasses = ['Bark','Bass_drum','Bicycle_bell','Bus','Car_passing_by','Male_speech_and_man_speaking',\n           'Male_speech_and_man_speaking,Male_singing','Female_speech_and_woman_speaking','Female_speech_and_woman_speaking,Whispering']\n\n# Reading wave files name\ndf_train_curated = pd.read_csv(\"../input/freesound-audio-tagging-2019/train_curated.csv\")  \n# Creating file names df for selected categories\ndf_train_curated = df_train_curated.loc[df_train_curated['labels'].isin(classes)]\ndf_files = df_train_curated.copy()\ndf_files.sort_values('labels', ascending=True, inplace=True);\ndf_files = df_files.reset_index(drop=True)\nprint(f'From dataset: {len(df_files)} Sound files')\ndf_files.head()","execution_count":null,"outputs":[]},{"metadata":{"id":"mRBVSdtbsVgj","outputId":"eca89a11-21ed-4d59-fb7f-c99186f479bb","trusted":true},"cell_type":"code","source":"df_files","execution_count":null,"outputs":[]},{"metadata":{"id":"bGCnHDB9lcgr","outputId":"dfe8332b-0482-4136-93a7-3202c07ffc2f","trusted":true},"cell_type":"code","source":"# combine Male / Female voices\nclasses = classes[:-2]\nclasses[-2]='Male_voice'\nclasses[-1]='Female_voice'\nmale = dict.fromkeys(['Male_speech_and_man_speaking','Male_speech_and_man_speaking,Male_singing'], 'Male_voice')    \nfemale = dict.fromkeys(['Female_speech_and_woman_speaking','Female_speech_and_woman_speaking,Whispering'],'Female_voice')  \ndf_files = df_files.replace(male)\ndf_files = df_files.replace(female)\nclasses","execution_count":null,"outputs":[]},{"metadata":{"id":"fDkqJjKjlcgv","outputId":"69825469-735b-42cd-99dd-3967b98edf42","trusted":true},"cell_type":"code","source":"#find the number of files for each class\nfor cls in classes: \n    files_len=len(df_files[df_files.labels==cls])  # The number of files \n    print(cls, files_len, 'files')","execution_count":null,"outputs":[]},{"metadata":{"id":"RHi4In8llcgz"},"cell_type":"markdown","source":"## $ 2. \\; EDA \\; and \\; Data \\; features \\; generation $ &#128204;","execution_count":null},{"metadata":{"id":"A52-Vf_Nlcg1","trusted":true},"cell_type":"code","source":"# New features dataframe\nfeatures_df = pd.DataFrame(columns=['file_name', 'avrg_freq','med_freq','std_Freq','var_freq',\n                                    'min_freq', 'max_freq',\n                                    'mfcc1','mfcc2','mfcc3','mfcc4','mfcc5','mfcc6','mfcc7','mfcc8',\n                                    'mfcc9','mfcc10','mfcc11','mfcc12','class',]) \n","execution_count":null,"outputs":[]},{"metadata":{"id":"mbOe6Ut8RmK7"},"cell_type":"markdown","source":"calculating mel frequency septrum for the audio files(.wav)\n","execution_count":null},{"metadata":{"id":"MPhpgC4ylcg5","outputId":"7b374187-0f32-4e68-828f-1786b97b5353","scrolled":false,"trusted":true},"cell_type":"code","source":"for cls in classes: \n    fnames = df_files[df_files['labels']==cls].fname\n    \n    for fname in fnames: #i in range(len(fnames)-1): \n            # Reading wav files\n            fs_rate, sig = scipy.io.wavfile.read(fname)\n            duration = len(sig) / fs_rate\n            audio_chnl = len(sig.shape)    # number of Channels\n            Ts = 1.0 / fs_rate            # Timestep between samples\n            time=np.linspace(0, duration, num = len(sig), endpoint=True)\n            time_len = len(time)\n\n            fltr_coef = 0.97 # filter coefficiant typical value\n            sig_o = np.append(sig[0], sig[1:] - fltr_coef * sig[:-1])  #  floating point\n\n            sig_freqs = []\n            static_feats = []\n\n            # windowing the signal\n            wind = np.hanning(len(sig)+1)[:-1]  \n            sig_s  = sig_o * wind\n\n            # mel-frequency ceptral coefficiens\n            mfcc = np.mean(librosa.feature.mfcc(y=sig_s, sr=fs_rate, n_mfcc=12).T,axis=0)\n\n            static_feats = process_fft()   # wave processing in the frequency domain\n\n            features_df.loc[len(features_df)] = [fname]+list(static_feats)+list(mfcc)+[cls]   ","execution_count":null,"outputs":[]},{"metadata":{"id":"tapyUpdalcg-"},"cell_type":"markdown","source":"### Clean data and save to csv file ","execution_count":null},{"metadata":{"id":"bNkmsTBZLRLe"},"cell_type":"markdown","source":"1. Deleting outliers.\n2. replacing empty features with mean values","execution_count":null},{"metadata":{"id":"UNylIBO6lcg-","outputId":"d4abe189-1878-4c2c-f84c-4cdc279623d0","trusted":true},"cell_type":"code","source":"features_df=features_df[features_df['max_freq']>0]    \n\nmap_std=features_df[features_df['std_Freq']>0].groupby('class')['std_Freq'].mean()\nmap_var=features_df[features_df['var_freq']>0].groupby('class')['var_freq'].mean()\n\nfeatures_df.loc[features_df['std_Freq']==0,'std_Freq'] = features_df[features_df['std_Freq']==0]\\\n                                                         .apply(lambda df_row: map_std.loc[df_row['class']], axis=1)\n\nfeatures_df.loc[features_df['var_freq']==0,'var_freq'] = features_df[features_df['var_freq']==0]\\\n                                                         .apply(lambda r: map_var.loc[r['class']], axis=1)\n\nfeatures_df.loc[features_df['min_freq']==0,'min_freq'] = features_df[features_df['min_freq']==0]\\\n                                                         .apply(lambda r: map_var.loc[r['class']], axis=1)\n\nfeatures_df.loc[features_df['med_freq']==0,'med_freq'] = features_df[features_df['med_freq']==0]\\\n                                                         .apply(lambda r: map_var.loc[r['class']], axis=1)\n\n# Save all features in csv file\nfeatures_df.to_csv('features.csv', encoding='utf-8') #  (index=False)\n\nb_s = '\\033[1m'\nb_e = '\\033[0m'\nprint(b_s,'\\033[34m ......{} files were recorded in features.csv'.format(len(features_df.file_name)),b_e)","execution_count":null,"outputs":[]},{"metadata":{"id":"W5t_1aLLlchD"},"cell_type":"markdown","source":"##Playing Audio files","execution_count":null},{"metadata":{"id":"a0oRZsStR_gZ"},"cell_type":"markdown","source":"male voice audio","execution_count":null},{"metadata":{"id":"wO7LhZ8nlchE","outputId":"f904d569-ffba-42ce-8b71-790bca7f2f7c","scrolled":true,"trusted":true},"cell_type":"code","source":"ipd.Audio('bfa6c58b.wav')     ","execution_count":null,"outputs":[]},{"metadata":{"id":"VNjQv3wElchQ","outputId":"60eb60c0-b7ab-4984-98bb-97a727c10252","trusted":true},"cell_type":"code","source":"features_df.describe()","execution_count":null,"outputs":[]},{"metadata":{"id":"ykHgxkyJlchV"},"cell_type":"markdown","source":"## View Features & Classes Correlations \n","execution_count":null},{"metadata":{"id":"ETEL1b9KlchW","outputId":"1d529997-00ed-4325-a3e1-9f17cb625c52","trusted":true},"cell_type":"code","source":"df_dumm = pd.get_dummies(features_df[features_df.columns[2:]])  \ndf_dumm.head()","execution_count":null,"outputs":[]},{"metadata":{"id":"8UEz4yYflcha","outputId":"740584a0-d329-4ff5-fe4a-f63a82809823","trusted":true},"cell_type":"code","source":"plt.figure(figsize=(16,10))\ncorr=df_dumm.corr()\nsns.heatmap(corr[(corr >= 0.1) | (corr <= -0.1)], \n            cmap='viridis', vmax=1.0, vmin=-1.0, linewidths=0.1,\n            annot=True, annot_kws={\"size\": 8}, square=True);\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"id":"QIFdrgFIlchc"},"cell_type":"markdown","source":"## Distribution of sounds Vs. frequency","execution_count":null},{"metadata":{"id":"_EfFpgAZlchd","outputId":"dbdb4479-f860-4e21-d39b-18ee186ac51f","trusted":true},"cell_type":"code","source":"plt.figure(figsize=(10,5))\nax = sns.kdeplot(df_dumm.max_freq[(df_dumm['class_Bass_drum'] == 1) ],\n                color=\"blue\", shade = True)\nax = sns.kdeplot(df_dumm.max_freq[(df_dumm['class_Bicycle_bell'] == 1) ],\n                ax =ax, color=\"red\", shade= True)\nax = sns.kdeplot(df_dumm.max_freq[(df_dumm['class_Bark'] == 1) ],\n                ax =ax, color=\"green\", shade= True)\nax = sns.kdeplot(df_dumm.max_freq[(df_dumm['class_Bus'] == 1) ],\n                ax =ax, color=\"yellow\", shade= True)\nax = sns.kdeplot(df_dumm.max_freq[(df_dumm['class_Male_voice'] == 1) ],\n                ax =ax, color=\"black\", shade= True)\nax = sns.kdeplot(df_dumm.max_freq[(df_dumm['class_Female_voice'] == 1) ],\n                ax =ax, color=\"orange\", shade= True)\nax = sns.kdeplot(df_dumm.max_freq[(df_dumm['class_Car_passing_by'] == 1) ],\n                ax =ax, color=\"grey\", shade= True)\nax.legend(['Bass drum', 'Bicycle_bell', 'Bark','Bus','Male_voice','Female_voice','Car passing'], loc='best')\nax.set_ylabel('Density')\nax.set_xlabel('max Frequencies [Hz]')\nax.set_title('Distribution of class noises Vs. max Frequencies', size = 13);","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"From the above figure , it can be seen that bass drum has a very high density, while the density of bark sound is also followed by the density of other sounds.","execution_count":null},{"metadata":{"id":"s54_JoA6lchg"},"cell_type":"markdown","source":"# 3. Mechine Learning","execution_count":null},{"metadata":{"id":"vqeNBQBVlchg","trusted":true},"cell_type":"code","source":"from sklearn.preprocessing import LabelEncoder\nfrom sklearn.model_selection import train_test_split, cross_val_score,\\\n    GridSearchCV\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import VotingClassifier, BaggingClassifier, \\\n    AdaBoostClassifier, GradientBoostingClassifier, RandomForestClassifier\nfrom sklearn.metrics import confusion_matrix, classification_report\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.utils import shuffle\nnp.random.seed(0)","execution_count":null,"outputs":[]},{"metadata":{"id":"vZwWImkylchj","trusted":true},"cell_type":"code","source":"def classification_results(y, y_pred, name='', add_rep=True):  # False\n    acc = accuracy_score(y, y_pred)\n                        \n    cm = pd.DataFrame(confusion_matrix(y, y_pred), \n                      index=classes, \n                      columns=classes)\n\n    print(name + ' accuracy: ', round(acc,4),'\\n') # round(acc,4)\n    print(cm,'\\n')\n    if (add_rep):\n        print(classification_report(y, y_pred))","execution_count":null,"outputs":[]},{"metadata":{"id":"Hu9HEH3ylchl","trusted":true},"cell_type":"code","source":"df = read_csv(\"features.csv\")\ntrain, test = train_test_split(df, test_size=0.3,  random_state=0)  #, random_state=0\n","execution_count":null,"outputs":[]},{"metadata":{"id":"2qWNdvkElcho","trusted":true},"cell_type":"code","source":"X_train = train[train.columns[2:-1]]\ny_train = train[train.columns[-1]]\nX_test = test[test.columns[2:-1]]\ny_test = test[test.columns[-1]]\n","execution_count":null,"outputs":[]},{"metadata":{"id":"Q6JudzYxlcht"},"cell_type":"markdown","source":"## K-nearest neighbors (KNN) classifier \n\n---\n\n","execution_count":null},{"metadata":{"id":"Ef66NoHRlchu","trusted":true},"cell_type":"code","source":"from sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.preprocessing import QuantileTransformer, RobustScaler, MinMaxScaler, Normalizer, StandardScaler\nfrom sklearn.model_selection import validation_curve\nfrom sklearn.metrics import roc_auc_score, average_precision_score, f1_score, log_loss, precision_score ","execution_count":null,"outputs":[]},{"metadata":{"id":"NWv2E4I4lchx","outputId":"91c81ac7-984c-48a6-8ad4-9fbb4a78c02a","trusted":true},"cell_type":"code","source":"scalers =np.array( [['Standard', StandardScaler()], \n                   ['MinMax', MinMaxScaler()], \n                   ['RobustScaler', RobustScaler()],\n                   ['Normalizer' , Normalizer()],\n                   ['QuantileTransformer', QuantileTransformer(n_quantiles=len(X_train))]])\n\nplt.figure(figsize=(12, 6))\nlegend =[]\nfor [scaler_name, scaler_func] in scalers:\n    for metric in ['manhattan', 'euclidean']:    #'hamming'\n        scaler = scaler_func\n        scaler.fit(X_train)\n        X = scaler.transform(X_train) \n        y = y_train\n        param='n_neighbors'\n        param_range = range(2,15,1)\n        train_scores, test_scores = validation_curve(KNeighborsClassifier(metric=metric),\n                                                     X, y,                                        \n                                                     param_name=param,\n                                                     param_range=param_range,\n                                                     scoring=\"accuracy\",\n                                                     cv=5) \n        \n        test_scores_mean = np.mean(test_scores, axis=1)\n        plt.plot(param_range, test_scores_mean);\n        legend.append(scaler_name+'-'+metric)\n\n    plt.title(\"Validation Curve Vs. KNN - on Train set\")\n    plt.xlabel(param)\n    plt.ylabel(\"Score - Accuracy\")\n    plt.ylim(0.65, 0.85)      \n    plt.legend(legend, loc='lower right')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"id":"VadFIGIwJI8C"},"cell_type":"markdown","source":"From the figure above we could see accuracy score is high for n_neighbour =4","execution_count":null},{"metadata":{"id":"UQWm6qYSlch0","trusted":true},"cell_type":"code","source":"knn = KNeighborsClassifier(n_neighbors=4, metric='manhattan')   #6,euclidean manhattan\n\n# Scale Transform and normalization   \nscaler = QuantileTransformer(n_quantiles=len(X_train)).fit(X_train)   # \n\nX = scaler.transform(X_train)  \ny = y_train\n\nknn.fit(X, y);","execution_count":null,"outputs":[]},{"metadata":{"id":"kAME96ZGlch3","trusted":true},"cell_type":"code","source":"y_train_pred = knn.predict(X)\ncm = confusion_matrix(y_true=y, y_pred=y_train_pred)\n","execution_count":null,"outputs":[]},{"metadata":{"id":"1zHNfAML3EBL","outputId":"be94cc4d-1525-4579-e5a8-397697e6c186","trusted":true},"cell_type":"code","source":"sns.set(font_scale=1.4)#for label size\nsns.heatmap(cm, annot=True,annot_kws={\"size\": 14}, fmt='g')","execution_count":null,"outputs":[]},{"metadata":{"id":"XP7WQHcCKyNJ","outputId":"da4f26e8-7ca8-45d9-853a-3fd495384874","trusted":true},"cell_type":"code","source":"print ('\\nClassification_report on Test set\\n',classification_report(y_true=y, y_pred=y_train_pred))","execution_count":null,"outputs":[]},{"metadata":{"id":"Ttwk932zlciB","trusted":true},"cell_type":"code","source":"X_test_knn = scaler.transform(X_test) \ny_test_pred = knn.predict(X_test_knn)","execution_count":null,"outputs":[]},{"metadata":{"id":"8L0wxc7hlciE","outputId":"568775d8-899e-488a-e839-c85fbc9c9030","trusted":true},"cell_type":"code","source":"cm = confusion_matrix(y_true=y_test, y_pred=y_test_pred)\nprint('\\nConfusion matrix on Test set:\\n')\nsns.set(font_scale=1.4)#for label size\nsns.heatmap(cm, annot=True,annot_kws={\"size\": 14}, fmt='g')","execution_count":null,"outputs":[]},{"metadata":{"id":"qW_bdlRPlciI","outputId":"47fddd1f-c1f2-4236-b2d4-72fc97be3269","trusted":true},"cell_type":"code","source":"print ('\\nClassification_report on Test set\\n',classification_report(y_true=y_test, y_pred=y_test_pred))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# CONCLUSION","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"1. By using K-Neasrest neighbours Algorithm we have achieved an accuracy of 0.81 in the test data\n2. It can be inferred from this project that MFCC (Mel -Frequency cepstral coefficient ) is very good representative of sound waves . ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}