{"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_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"## Import the libraries\n","metadata":{"execution":{"iopub.status.busy":"2022-02-11T15:15:42.09471Z","iopub.execute_input":"2022-02-11T15:15:42.095103Z","iopub.status.idle":"2022-02-11T15:15:42.099724Z","shell.execute_reply.started":"2022-02-11T15:15:42.095016Z","shell.execute_reply":"2022-02-11T15:15:42.098645Z"}}},{"cell_type":"code","source":"!pip install pyunpack\n!pip install patool\n!pip install py7zr\n!pip install sounddevice\n!pip install noisereduce\n!pip install librosa\n! pip install python_speech_features\n! pip install tensorflow==2.4\n! pip install malaya_speech\n! pip install webrtcvad","metadata":{"execution":{"iopub.status.busy":"2022-04-23T13:24:08.181023Z","iopub.execute_input":"2022-04-23T13:24:08.181266Z","iopub.status.idle":"2022-04-23T13:26:44.401433Z","shell.execute_reply.started":"2022-04-23T13:24:08.181243Z","shell.execute_reply":"2022-04-23T13:26:44.400388Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nfrom py7zr import unpack_7zarchive\nimport shutil\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nimport librosa\nimport IPython.display as ipd\nfrom scipy.io import wavfile\n\nimport noisereduce as nr\nimport tensorflow \nfrom malaya_speech import Pipeline\n\nimport malaya_speech\nimport os\n\nfrom python_speech_features import mfcc\n\nfrom sklearn.preprocessing import LabelEncoder\nimport seaborn as sn","metadata":{"execution":{"iopub.status.busy":"2022-04-23T13:26:44.403202Z","iopub.execute_input":"2022-04-23T13:26:44.403541Z","iopub.status.idle":"2022-04-23T13:26:49.208692Z","shell.execute_reply.started":"2022-04-23T13:26:44.403503Z","shell.execute_reply":"2022-04-23T13:26:49.207744Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"shutil.register_unpack_format('7zip', ['.7z'], unpack_7zarchive)\nshutil.unpack_archive('/kaggle/input/tensorflow-speech-recognition-challenge/train.7z', '/kaggle/working/tensorflow-speech-recognition-challenge/train/')","metadata":{"execution":{"iopub.status.busy":"2022-04-23T13:26:49.210572Z","iopub.execute_input":"2022-04-23T13:26:49.210910Z","iopub.status.idle":"2022-04-23T13:36:06.691119Z","shell.execute_reply.started":"2022-04-23T13:26:49.210875Z","shell.execute_reply":"2022-04-23T13:36:06.690116Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# from pyunpack import Archive\n# import shutil\n# if not os.path.exists('/kaggle/working/tensorflow-speech-recognition-challenge/train/'):\n#     os.makedirs('/kaggle/working/tensorflow-speech-recognition-challenge/train/')\n# Archive('/kaggle/input/tensorflow-speech-recognition-challenge/train.7z').extractall('/kaggle/working/tensorflow-speech-recognition-challenge/train/')\n\n#for dirname, _, filenames in os.walk('/kaggle/working/tensorflow-speech-recognition-challenge/train/train/audio'):\n #   for filename in filename[:5]:\n  #      print(os.path.join(dirname, filename))","metadata":{"execution":{"iopub.status.busy":"2022-04-23T13:36:06.692866Z","iopub.execute_input":"2022-04-23T13:36:06.693197Z","iopub.status.idle":"2022-04-23T13:36:06.697319Z","shell.execute_reply.started":"2022-04-23T13:36:06.693160Z","shell.execute_reply":"2022-04-23T13:36:06.696537Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# <center> Implementing the Speech Recognition Model in Python\n**Dataset used for our Speech Recognition Project**\n\n__You can download the dataset from__ [here](https://www.kaggle.com/c/tensorflow-speech-recognition-challenge).\n    \nTensorFlow recently released the Speech Commands Datasets. It includes 65,000 one-second long utterances of 30 short words, by thousands of different people. We’ll build a speech recognition system that understands simple spoken commands. <br>    ","metadata":{}},{"cell_type":"markdown","source":"**Data Exploration and Visualization**\n\nData Exploration and Visualization helps us to understand the data as well as pre-processing steps in a better way. \n\n**Visualization of Audio signal in time series domain**\n\nNow, we’ll visualize the audio signal in the time series domain:","metadata":{}},{"cell_type":"code","source":"train_audio_path = '/kaggle/working/tensorflow-speech-recognition-challenge/train/train/audio/'","metadata":{"execution":{"iopub.status.busy":"2022-04-23T13:36:06.698687Z","iopub.execute_input":"2022-04-23T13:36:06.699214Z","iopub.status.idle":"2022-04-23T13:36:06.709956Z","shell.execute_reply.started":"2022-04-23T13:36:06.699176Z","shell.execute_reply":"2022-04-23T13:36:06.709127Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Accessing each file in data**","metadata":{}},{"cell_type":"code","source":"#!apt-get install -y p7zip-full\n#!7z x ../input/tensorflow-speech-recognition-challenge/train.7z","metadata":{"execution":{"iopub.status.busy":"2022-04-23T13:36:06.711188Z","iopub.execute_input":"2022-04-23T13:36:06.711533Z","iopub.status.idle":"2022-04-23T13:36:06.717823Z","shell.execute_reply.started":"2022-04-23T13:36:06.711498Z","shell.execute_reply":"2022-04-23T13:36:06.716939Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"samples, sample_rate = librosa.load(train_audio_path+'on/5a3712c9_nohash_1.wav', sr = 16000)\nfig = plt.figure(figsize=(14, 8))\nax1 = fig.add_subplot(211)\nax1.set_title('Raw wave of ' + '../input/train/audio/on/0a7c2a8d_nohash_0.wav')\nax1.set_xlabel('time')\nax1.set_ylabel('Amplitude')\nax1.plot(np.linspace(0, sample_rate/len(samples), sample_rate), samples)","metadata":{"execution":{"iopub.status.busy":"2022-04-23T13:36:06.719002Z","iopub.execute_input":"2022-04-23T13:36:06.719462Z","iopub.status.idle":"2022-04-23T13:36:06.900535Z","shell.execute_reply.started":"2022-04-23T13:36:06.719427Z","shell.execute_reply":"2022-04-23T13:36:06.899554Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Sampling rate **\n\nLet us now look at the sampling rate of the audio signals","metadata":{}},{"cell_type":"code","source":"ipd.Audio(samples, rate=sample_rate)","metadata":{"execution":{"iopub.status.busy":"2022-04-23T13:36:06.903466Z","iopub.execute_input":"2022-04-23T13:36:06.903818Z","iopub.status.idle":"2022-04-23T13:36:06.912195Z","shell.execute_reply.started":"2022-04-23T13:36:06.903782Z","shell.execute_reply":"2022-04-23T13:36:06.911394Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(sample_rate)\nsig1=samples\nfs=sample_rate\nsr=fs","metadata":{"execution":{"iopub.status.busy":"2022-04-23T13:36:06.914078Z","iopub.execute_input":"2022-04-23T13:36:06.914615Z","iopub.status.idle":"2022-04-23T13:36:06.919747Z","shell.execute_reply.started":"2022-04-23T13:36:06.914575Z","shell.execute_reply":"2022-04-23T13:36:06.918902Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"time = np.linspace(0, len(sig1 - 1) / fs, len(sig1 - 1))\nreduced_noise1 = nr.reduce_noise(y=sig1, sr=fs,stationary=True)\nplt.plot(time, reduced_noise1)  # plot in seconds\n#reduced_noise2 = nr.reduce_noise(y=sig2, sr=fs,stationary=True)\n#plt.plot(time, reduced_noise2)  # plot in seconds\n#plt.title(\"Voice Signal\")\nplt.xlabel(\"Time [seconds]\")\nplt.ylabel(\"Voice amplitude\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-04-23T13:36:06.921268Z","iopub.execute_input":"2022-04-23T13:36:06.921894Z","iopub.status.idle":"2022-04-23T13:36:07.630392Z","shell.execute_reply.started":"2022-04-23T13:36:06.921859Z","shell.execute_reply":"2022-04-23T13:36:07.629568Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ipd.Audio(reduced_noise1, rate=sample_rate)","metadata":{"execution":{"iopub.status.busy":"2022-04-23T13:36:07.631804Z","iopub.execute_input":"2022-04-23T13:36:07.632152Z","iopub.status.idle":"2022-04-23T13:36:07.642548Z","shell.execute_reply.started":"2022-04-23T13:36:07.632114Z","shell.execute_reply":"2022-04-23T13:36:07.641688Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Silence Removal\nvad = malaya_speech.vad.webrtc()\ny=reduced_noise1\ny_= malaya_speech.resample(y, sr, 16000)\ny_ = malaya_speech.astype.float_to_int(y_)\nframes = malaya_speech.generator.frames(y, 30, sr)\nframes_ = list(malaya_speech.generator.frames(y_, 30, 16000, append_ending_trail = False))\nframes_webrtc = [(frames[no], vad(frame)) for no, frame in enumerate(frames_)]\ny_ = malaya_speech.combine.without_silent(frames_webrtc)\ny_","metadata":{"execution":{"iopub.status.busy":"2022-04-23T13:36:07.644028Z","iopub.execute_input":"2022-04-23T13:36:07.644682Z","iopub.status.idle":"2022-04-23T13:36:07.808511Z","shell.execute_reply.started":"2022-04-23T13:36:07.644644Z","shell.execute_reply":"2022-04-23T13:36:07.807749Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ipd.Audio(y_, rate = sr )","metadata":{"execution":{"iopub.status.busy":"2022-04-23T13:36:07.809733Z","iopub.execute_input":"2022-04-23T13:36:07.810067Z","iopub.status.idle":"2022-04-23T13:36:07.818259Z","shell.execute_reply.started":"2022-04-23T13:36:07.810032Z","shell.execute_reply":"2022-04-23T13:36:07.817207Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"zero = np.zeros((1*sr-y_.shape[0]))\nsignal = np.concatenate((y_,zero))\nsignal.shape\ntime = np.linspace(0, len(signal - 1) / fs, len(signal - 1))","metadata":{"execution":{"iopub.status.busy":"2022-04-23T13:36:07.819769Z","iopub.execute_input":"2022-04-23T13:36:07.820427Z","iopub.status.idle":"2022-04-23T13:36:07.826295Z","shell.execute_reply.started":"2022-04-23T13:36:07.820380Z","shell.execute_reply":"2022-04-23T13:36:07.825512Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(time,signal)","metadata":{"execution":{"iopub.status.busy":"2022-04-23T13:36:07.829074Z","iopub.execute_input":"2022-04-23T13:36:07.829339Z","iopub.status.idle":"2022-04-23T13:36:07.973642Z","shell.execute_reply.started":"2022-04-23T13:36:07.829308Z","shell.execute_reply":"2022-04-23T13:36:07.972750Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels=os.listdir(train_audio_path)","metadata":{"execution":{"iopub.status.busy":"2022-04-23T13:36:07.974908Z","iopub.execute_input":"2022-04-23T13:36:07.975242Z","iopub.status.idle":"2022-04-23T13:36:07.980872Z","shell.execute_reply.started":"2022-04-23T13:36:07.975207Z","shell.execute_reply":"2022-04-23T13:36:07.979832Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#find count of each label and plot bar graph\nno_of_recordings=[]\nfor label in labels:\n    waves = [f for f in os.listdir(train_audio_path + '/'+ label) if f.endswith('.wav')]\n    no_of_recordings.append(len(waves))\n    \n#plot\nplt.figure(figsize=(30,5))\nindex = np.arange(len(labels))\nplt.bar(index, no_of_recordings)\nplt.xlabel('Commands', fontsize=12)\nplt.ylabel('No of recordings', fontsize=12)\nplt.xticks(index, labels, fontsize=15, rotation=60)\nplt.title('No. of recordings for each command')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-04-23T13:36:07.982247Z","iopub.execute_input":"2022-04-23T13:36:07.982587Z","iopub.status.idle":"2022-04-23T13:36:08.318565Z","shell.execute_reply.started":"2022-04-23T13:36:07.982554Z","shell.execute_reply":"2022-04-23T13:36:08.317776Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Words used","metadata":{}},{"cell_type":"code","source":"labels=[\"zero\",\"one\",\"two\",\"three\",\"four\",\"five\",\"six\",\"seven\",\"eight\",\"nine\"]","metadata":{"execution":{"iopub.status.busy":"2022-04-23T13:36:08.319852Z","iopub.execute_input":"2022-04-23T13:36:08.320348Z","iopub.status.idle":"2022-04-23T13:36:08.325323Z","shell.execute_reply.started":"2022-04-23T13:36:08.320287Z","shell.execute_reply":"2022-04-23T13:36:08.324159Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## **Preprocessing the audio waves**\n\nlet us read the audio waves and use the below-preprocessing steps :\n\n* Noise Reduction\n* Silence Removal\n* Extracting MFCCs\n\nLet us define these preprocessing steps in the below code snippet:","metadata":{}},{"cell_type":"code","source":"sr=16000\nvad = malaya_speech.vad.webrtc()\nall_wave = []\nall_label = []\nfor label in labels:\n    print(label)\n    waves = [f for f in os.listdir(train_audio_path + '/'+ label) if f.endswith('.wav')]\n    for wav in waves:\n        samples, sample_rate = librosa.load(train_audio_path + '/' + label + '/' + wav, sr = 16000)\n        samples = nr.reduce_noise(y=samples, sr=sr,stationary=True)\n        y_= malaya_speech.resample(samples, sr, 16000)\n        y_ = malaya_speech.astype.float_to_int(y_)\n        frames = malaya_speech.generator.frames(samples, 30, sr)\n        frames_ = list(malaya_speech.generator.frames(y_, 30, 16000, append_ending_trail = False))\n        frames_webrtc = [(frames[no], vad(frame)) for no, frame in enumerate(frames_)]\n        y_ = malaya_speech.combine.without_silent(frames_webrtc)\n        zero = np.zeros(((1*sr+4000)-y_.shape[0]))\n        signal = np.concatenate((y_,zero))\n        all_wave.append(signal)\n        all_label.append(label)","metadata":{"execution":{"iopub.status.busy":"2022-04-23T13:36:08.326799Z","iopub.execute_input":"2022-04-23T13:36:08.327129Z","iopub.status.idle":"2022-04-23T13:47:10.526618Z","shell.execute_reply.started":"2022-04-23T13:36:08.327096Z","shell.execute_reply":"2022-04-23T13:47:10.525660Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(np.array(all_wave).shape)\nprint(np.array(all_label).shape)\ntime = np.linspace(0, len(signal - 1) / fs, len(signal - 1))\nplt.plot(time,np.array(all_wave)[2000,:])\nprint(np.array(all_label)[2000])\nipd.Audio(np.array(all_wave)[2000,:], rate = sr )","metadata":{"execution":{"iopub.status.busy":"2022-04-23T13:47:10.528162Z","iopub.execute_input":"2022-04-23T13:47:10.528753Z","iopub.status.idle":"2022-04-23T13:47:21.470086Z","shell.execute_reply.started":"2022-04-23T13:47:10.528703Z","shell.execute_reply":"2022-04-23T13:47:21.469089Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"all_mfcc=[]\nfor wave in all_wave:\n    i=0\n    mfcc_feat = mfcc(wave , fs, winlen=256/fs, winstep=256/(2*fs), numcep=13, nfilt=26, nfft=256,\n                 lowfreq=0, highfreq=fs/2, preemph=0.97, ceplifter=22, appendEnergy=True, winfunc=np.hamming)\n    mfcc_feat= np.transpose(mfcc_feat)\n    all_mfcc.append(mfcc_feat)\n    ","metadata":{"execution":{"iopub.status.busy":"2022-04-23T13:47:21.471566Z","iopub.execute_input":"2022-04-23T13:47:21.471925Z","iopub.status.idle":"2022-04-23T13:48:32.700206Z","shell.execute_reply.started":"2022-04-23T13:47:21.471888Z","shell.execute_reply":"2022-04-23T13:48:32.699153Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(np.array(all_mfcc).shape)\nprint(np.array(all_label).shape)\nd1=np.array(all_mfcc).shape[1]\nd2=np.array(all_mfcc).shape[2]\nd=d1*d2\nprint(d)","metadata":{"execution":{"iopub.status.busy":"2022-04-23T13:48:32.701467Z","iopub.execute_input":"2022-04-23T13:48:32.702058Z","iopub.status.idle":"2022-04-23T13:48:33.216436Z","shell.execute_reply.started":"2022-04-23T13:48:32.702019Z","shell.execute_reply":"2022-04-23T13:48:33.214856Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"op_mfcc=np.array(all_mfcc)\nop_mfcc=op_mfcc.reshape(np.array(all_mfcc).shape[0],-1)\nop_mfcc.shape","metadata":{"execution":{"iopub.status.busy":"2022-04-23T13:48:33.220278Z","iopub.execute_input":"2022-04-23T13:48:33.220573Z","iopub.status.idle":"2022-04-23T13:48:33.536561Z","shell.execute_reply.started":"2022-04-23T13:48:33.220543Z","shell.execute_reply":"2022-04-23T13:48:33.535534Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#all_label = all_label.tolist()\n\nle = LabelEncoder()\ny=le.fit_transform(all_label)\nclasses= list(le.classes_)","metadata":{"execution":{"iopub.status.busy":"2022-04-23T13:48:33.538367Z","iopub.execute_input":"2022-04-23T13:48:33.538739Z","iopub.status.idle":"2022-04-23T13:48:33.551447Z","shell.execute_reply.started":"2022-04-23T13:48:33.538683Z","shell.execute_reply":"2022-04-23T13:48:33.550665Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## **Model based on ANN** ","metadata":{}},{"cell_type":"code","source":"! pip install --upgrade tensorflow\n! pip install --upgrade tensorflow-gpu\n! pip install keras==2.3.1","metadata":{"execution":{"iopub.status.busy":"2022-04-23T13:48:33.552996Z","iopub.execute_input":"2022-04-23T13:48:33.553345Z","iopub.status.idle":"2022-04-23T13:51:16.610021Z","shell.execute_reply.started":"2022-04-23T13:48:33.553310Z","shell.execute_reply":"2022-04-23T13:51:16.609037Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.optimizers import SGD\nfrom keras.constraints import maxnorm\nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras.layers import Conv2D, Flatten, Dense,Dropout\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint","metadata":{"execution":{"iopub.status.busy":"2022-04-23T13:51:16.612809Z","iopub.execute_input":"2022-04-23T13:51:16.613163Z","iopub.status.idle":"2022-04-23T13:51:16.663306Z","shell.execute_reply.started":"2022-04-23T13:51:16.613123Z","shell.execute_reply":"2022-04-23T13:51:16.662447Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y=tensorflow.keras.utils.to_categorical(y, num_classes=len(labels), dtype='float32')\ny.shape","metadata":{"execution":{"iopub.status.busy":"2022-04-23T13:51:16.664579Z","iopub.execute_input":"2022-04-23T13:51:16.665173Z","iopub.status.idle":"2022-04-23T13:51:16.674472Z","shell.execute_reply.started":"2022-04-23T13:51:16.665135Z","shell.execute_reply":"2022-04-23T13:51:16.673651Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nx_tr, x_val, y_tr, y_val= train_test_split(op_mfcc,np.array(y),stratify=y,test_size = 0.2,random_state=777,shuffle=True)","metadata":{"execution":{"iopub.status.busy":"2022-04-23T13:51:16.676799Z","iopub.execute_input":"2022-04-23T13:51:16.677862Z","iopub.status.idle":"2022-04-23T13:51:17.439886Z","shell.execute_reply.started":"2022-04-23T13:51:16.677824Z","shell.execute_reply":"2022-04-23T13:51:17.438973Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(x_tr.shape)\nprint(y_tr.shape)\nprint(x_val.shape)\nprint(y_val.shape)","metadata":{"execution":{"iopub.status.busy":"2022-04-23T13:51:17.441586Z","iopub.execute_input":"2022-04-23T13:51:17.442098Z","iopub.status.idle":"2022-04-23T13:51:17.448282Z","shell.execute_reply.started":"2022-04-23T13:51:17.442059Z","shell.execute_reply":"2022-04-23T13:51:17.447392Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### **Model Architecture**","metadata":{}},{"cell_type":"code","source":"#Model Architecture\nmodel = Sequential()\nmodel.add(Dense(500, activation='relu', input_shape=(d,), kernel_constraint=maxnorm(3)))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(100, activation='relu', kernel_constraint=maxnorm(3)))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(80, activation='relu', kernel_constraint=maxnorm(3)))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(len(classes), activation='softmax' , kernel_constraint=maxnorm(3)))","metadata":{"execution":{"iopub.status.busy":"2022-04-23T14:03:02.205660Z","iopub.execute_input":"2022-04-23T14:03:02.206115Z","iopub.status.idle":"2022-04-23T14:03:02.251506Z","shell.execute_reply.started":"2022-04-23T14:03:02.206079Z","shell.execute_reply":"2022-04-23T14:03:02.250771Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tensorflow.keras.utils.plot_model(model, 'model.png',show_shapes=True)","metadata":{"execution":{"iopub.status.busy":"2022-04-23T14:03:03.797272Z","iopub.execute_input":"2022-04-23T14:03:03.797605Z","iopub.status.idle":"2022-04-23T14:03:04.209658Z","shell.execute_reply.started":"2022-04-23T14:03:03.797572Z","shell.execute_reply":"2022-04-23T14:03:04.208667Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(loss='categorical_crossentropy',optimizer='adamax',metrics=['accuracy'])\n","metadata":{"execution":{"iopub.status.busy":"2022-04-23T14:03:09.612310Z","iopub.execute_input":"2022-04-23T14:03:09.612643Z","iopub.status.idle":"2022-04-23T14:03:09.628768Z","shell.execute_reply.started":"2022-04-23T14:03:09.612608Z","shell.execute_reply":"2022-04-23T14:03:09.627894Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"es = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=10, min_delta=0.0001) \nmc = ModelCheckpoint('best_model.hdf5', monitor='val_acc', verbose=1, save_best_only=True, mode='max')","metadata":{"execution":{"iopub.status.busy":"2022-04-23T14:03:11.818061Z","iopub.execute_input":"2022-04-23T14:03:11.818484Z","iopub.status.idle":"2022-04-23T14:03:11.823950Z","shell.execute_reply.started":"2022-04-23T14:03:11.818438Z","shell.execute_reply":"2022-04-23T14:03:11.822927Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#18932\n300*64","metadata":{"execution":{"iopub.status.busy":"2022-04-23T14:03:13.709946Z","iopub.execute_input":"2022-04-23T14:03:13.710297Z","iopub.status.idle":"2022-04-23T14:03:13.718590Z","shell.execute_reply.started":"2022-04-23T14:03:13.710267Z","shell.execute_reply":"2022-04-23T14:03:13.717775Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history=model.fit(x_tr, y_tr,validation_data=(x_val,y_val), epochs=300, batch_size=64)","metadata":{"execution":{"iopub.status.busy":"2022-04-23T14:03:14.479836Z","iopub.execute_input":"2022-04-23T14:03:14.480170Z","iopub.status.idle":"2022-04-23T14:08:24.444978Z","shell.execute_reply.started":"2022-04-23T14:03:14.480141Z","shell.execute_reply":"2022-04-23T14:08:24.444143Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_score = model.evaluate(x_tr, y_tr, batch_size=12)\nprint(train_score)\n\nprint('----------------Training Complete-----------------')\n\ntest_score = model.evaluate(x_val, y_val, batch_size = 12)\nprint(test_score)","metadata":{"execution":{"iopub.status.busy":"2022-04-23T14:08:27.670988Z","iopub.execute_input":"2022-04-23T14:08:27.671766Z","iopub.status.idle":"2022-04-23T14:08:31.543288Z","shell.execute_reply.started":"2022-04-23T14:08:27.671698Z","shell.execute_reply":"2022-04-23T14:08:31.542422Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history.history.keys()","metadata":{"execution":{"iopub.status.busy":"2022-04-23T14:08:34.789584Z","iopub.execute_input":"2022-04-23T14:08:34.789962Z","iopub.status.idle":"2022-04-23T14:08:34.795372Z","shell.execute_reply.started":"2022-04-23T14:08:34.789929Z","shell.execute_reply":"2022-04-23T14:08:34.794530Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from matplotlib import pyplot\npyplot.plot(history.history['loss'], label='train')\npyplot.plot(history.history['val_loss'], label='test')\npyplot.legend()\npyplot.show()","metadata":{"execution":{"iopub.status.busy":"2022-04-23T14:08:37.079047Z","iopub.execute_input":"2022-04-23T14:08:37.079477Z","iopub.status.idle":"2022-04-23T14:08:37.311730Z","shell.execute_reply.started":"2022-04-23T14:08:37.079440Z","shell.execute_reply":"2022-04-23T14:08:37.310900Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'val'], loc='upper left')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-04-23T14:08:39.793616Z","iopub.execute_input":"2022-04-23T14:08:39.794025Z","iopub.status.idle":"2022-04-23T14:08:39.955632Z","shell.execute_reply.started":"2022-04-23T14:08:39.793991Z","shell.execute_reply":"2022-04-23T14:08:39.954629Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_predict=model.predict(x_val)\nconf_mat=tensorflow.math.confusion_matrix(np.argmax(y_val,axis=1) , np.argmax(y_predict,axis=1))","metadata":{"execution":{"iopub.status.busy":"2022-04-23T14:08:43.754463Z","iopub.execute_input":"2022-04-23T14:08:43.754847Z","iopub.status.idle":"2022-04-23T14:08:44.022703Z","shell.execute_reply.started":"2022-04-23T14:08:43.754805Z","shell.execute_reply":"2022-04-23T14:08:44.021733Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_cm = pd.DataFrame(np.array(conf_mat), index = [i for i in classes],\n                  columns = [i for i in classes])\nplt.figure(figsize = (13,7))\nax = sn.heatmap(df_cm, annot=True)\nplt.title(\"Confusion Matrix\", fontsize=20)\nplt.ylabel(\"True Class\"     , fontsize=20)\nplt.xlabel(\"Predicted Class\", fontsize=20)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-04-23T14:08:47.216452Z","iopub.execute_input":"2022-04-23T14:08:47.216876Z","iopub.status.idle":"2022-04-23T14:08:47.833870Z","shell.execute_reply.started":"2022-04-23T14:08:47.216839Z","shell.execute_reply":"2022-04-23T14:08:47.833042Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_val[1].shape\nmodel.predict(x_val[1].reshape((1,d)))","metadata":{"execution":{"iopub.status.busy":"2022-04-23T14:09:14.919226Z","iopub.execute_input":"2022-04-23T14:09:14.919548Z","iopub.status.idle":"2022-04-23T14:09:14.963475Z","shell.execute_reply.started":"2022-04-23T14:09:14.919518Z","shell.execute_reply":"2022-04-23T14:09:14.962647Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Define the function that predicts text for the given audio:","metadata":{}},{"cell_type":"code","source":"def predict(audio):\n    print(samples.shape)\n    prob=model.predict(audio)\n    index=np.argmax(prob[0])\n    return classes[index]","metadata":{"execution":{"iopub.status.busy":"2022-04-23T14:09:18.669135Z","iopub.execute_input":"2022-04-23T14:09:18.669465Z","iopub.status.idle":"2022-04-23T14:09:18.674005Z","shell.execute_reply.started":"2022-04-23T14:09:18.669435Z","shell.execute_reply":"2022-04-23T14:09:18.672826Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Prediction time! Make predictions on the validation data:","metadata":{}},{"cell_type":"code","source":"import random\nindex=random.randint(0,len(x_val)-1)\nprint(index)\nsamples=x_val[index]\nprint(\"Audio:\",classes[np.argmax(y_val[index])])\n#ipd.Audio(np.array(all_wave)[index,:], rate=16000)","metadata":{"execution":{"iopub.status.busy":"2022-04-23T14:09:27.724738Z","iopub.execute_input":"2022-04-23T14:09:27.725095Z","iopub.status.idle":"2022-04-23T14:09:27.733910Z","shell.execute_reply.started":"2022-04-23T14:09:27.725059Z","shell.execute_reply":"2022-04-23T14:09:27.732454Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Text:\",predict(samples.reshape(1,d)))","metadata":{"execution":{"iopub.status.busy":"2022-04-23T14:09:28.718601Z","iopub.execute_input":"2022-04-23T14:09:28.718990Z","iopub.status.idle":"2022-04-23T14:09:28.763692Z","shell.execute_reply.started":"2022-04-23T14:09:28.718954Z","shell.execute_reply":"2022-04-23T14:09:28.762806Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.models import load_model\nmodel.save(\"numbers.h5\")","metadata":{"execution":{"iopub.status.busy":"2022-04-23T14:09:31.869016Z","iopub.execute_input":"2022-04-23T14:09:31.869438Z","iopub.status.idle":"2022-04-23T14:09:31.938477Z","shell.execute_reply.started":"2022-04-23T14:09:31.869399Z","shell.execute_reply":"2022-04-23T14:09:31.937598Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}