{"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":"2023-01-12T23:41:16.63057Z","iopub.execute_input":"2023-01-12T23:41:16.630955Z","iopub.status.idle":"2023-01-12T23:43:09.742998Z","shell.execute_reply.started":"2023-01-12T23:41:16.63087Z","shell.execute_reply":"2023-01-12T23:43:09.742001Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"! pip install --upgrade transformers","metadata":{"execution":{"iopub.status.busy":"2023-01-12T23:44:46.281189Z","iopub.execute_input":"2023-01-12T23:44:46.281569Z","iopub.status.idle":"2023-01-12T23:45:00.553177Z","shell.execute_reply.started":"2023-01-12T23:44:46.281525Z","shell.execute_reply":"2023-01-12T23:45:00.552223Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pip install git+https://github.com/huggingface/transformers","metadata":{"execution":{"iopub.status.busy":"2023-01-12T23:51:52.100864Z","iopub.execute_input":"2023-01-12T23:51:52.101236Z","iopub.status.idle":"2023-01-12T23:52:32.107128Z","shell.execute_reply.started":"2023-01-12T23:51:52.101199Z","shell.execute_reply":"2023-01-12T23:52:32.106195Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np                        # linear algebra library\nimport pandas as pd                       # data frames processing\nimport matplotlib.pyplot as plt          # visualization library\nimport seaborn as sn                      # visualization library\n\n\n# audio processing library\nimport librosa                          \nimport IPython.display as ipd            \nfrom scipy.io import wavfile\nimport noisereduce as nr\nfrom malaya_speech import Pipeline\nimport malaya_speech\nfrom python_speech_features import mfcc\nfrom sklearn.preprocessing import LabelEncoder\n\n\n# unpacking the dataset\nfrom py7zr import unpack_7zarchive    \n\n#operating system libraries\nimport shutil\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nimport tensorflow \nimport os","metadata":{"execution":{"iopub.status.busy":"2023-01-12T23:52:35.448981Z","iopub.execute_input":"2023-01-12T23:52:35.449311Z","iopub.status.idle":"2023-01-12T23:52:42.359032Z","shell.execute_reply.started":"2023-01-12T23:52:35.449279Z","shell.execute_reply":"2023-01-12T23:52:42.357991Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# unpacking the dataset\nshutil.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":"2023-01-12T23:52:45.208964Z","iopub.execute_input":"2023-01-12T23:52:45.209351Z","iopub.status.idle":"2023-01-13T00:01:55.616351Z","shell.execute_reply.started":"2023-01-12T23:52:45.209315Z","shell.execute_reply":"2023-01-13T00:01:55.615365Z"},"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    \nIt is a set of 10 numbers each is repeated 2000 times with different accents and different back ground conditions. TensorFlow 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>    \n    \n__You can download the dataset from__ [here](https://www.kaggle.com/c/tensorflow-speech-recognition-challenge).\n","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","metadata":{}},{"cell_type":"code","source":"train_audio_path = '/kaggle/working/tensorflow-speech-recognition-challenge/train/train/audio/' #path of the training data","metadata":{"execution":{"iopub.status.busy":"2023-01-13T00:05:31.400201Z","iopub.execute_input":"2023-01-13T00:05:31.400583Z","iopub.status.idle":"2023-01-13T00:05:31.404932Z","shell.execute_reply.started":"2023-01-13T00:05:31.400548Z","shell.execute_reply":"2023-01-13T00:05:31.403707Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Accessing each file in data**","metadata":{}},{"cell_type":"code","source":"samples, sample_rate = librosa.load(train_audio_path+'on/5a3712c9_nohash_1.wav', sr = 16000)  # loading a sample to be explored carefully\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":"2023-01-13T00:05:33.580634Z","iopub.execute_input":"2023-01-13T00:05:33.581007Z","iopub.status.idle":"2023-01-13T00:05:33.765171Z","shell.execute_reply.started":"2023-01-13T00:05:33.580969Z","shell.execute_reply":"2023-01-13T00:05:33.764227Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fs=16000\nipd.Audio(samples, rate=fs)  #listen to audio file before noise reduction\nprint(\"Sample Rate:\",fs)\nsr=fs","metadata":{"execution":{"iopub.status.busy":"2023-01-13T00:05:36.268812Z","iopub.execute_input":"2023-01-13T00:05:36.26916Z","iopub.status.idle":"2023-01-13T00:05:36.275669Z","shell.execute_reply.started":"2023-01-13T00:05:36.269128Z","shell.execute_reply":"2023-01-13T00:05:36.274702Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Noise Reduction\ntime = np.linspace(0, len(samples - 1) / fs, len(samples - 1))\nreduced_noise1 = nr.reduce_noise(y=samples, sr=fs,stationary=True)\nplt.plot(time, reduced_noise1)  # plot in seconds\nplt.xlabel(\"Time [seconds]\")\nplt.ylabel(\"Voice amplitude\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-01-13T00:05:37.824257Z","iopub.execute_input":"2023-01-13T00:05:37.824575Z","iopub.status.idle":"2023-01-13T00:05:38.521529Z","shell.execute_reply.started":"2023-01-13T00:05:37.824544Z","shell.execute_reply":"2023-01-13T00:05:38.520489Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ipd.Audio(reduced_noise1, rate=sample_rate)  #listen to audio file after noise reduction","metadata":{"execution":{"iopub.status.busy":"2023-01-13T00:05:41.015339Z","iopub.execute_input":"2023-01-13T00:05:41.015662Z","iopub.status.idle":"2023-01-13T00:05:41.022959Z","shell.execute_reply.started":"2023-01-13T00:05:41.015632Z","shell.execute_reply":"2023-01-13T00:05:41.021922Z"},"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":"2023-01-13T00:05:45.466717Z","iopub.execute_input":"2023-01-13T00:05:45.467093Z","iopub.status.idle":"2023-01-13T00:05:45.70179Z","shell.execute_reply.started":"2023-01-13T00:05:45.467061Z","shell.execute_reply":"2023-01-13T00:05:45.700923Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ipd.Audio(y_, rate = sr )     #listen to audio file after noise reduction","metadata":{"execution":{"iopub.status.busy":"2023-01-13T00:05:47.759865Z","iopub.execute_input":"2023-01-13T00:05:47.760197Z","iopub.status.idle":"2023-01-13T00:05:47.767526Z","shell.execute_reply.started":"2023-01-13T00:05:47.760167Z","shell.execute_reply":"2023-01-13T00:05:47.766494Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# padding signal with zeros\nzero = 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":"2023-01-13T00:05:51.512078Z","iopub.execute_input":"2023-01-13T00:05:51.512466Z","iopub.status.idle":"2023-01-13T00:05:51.521713Z","shell.execute_reply.started":"2023-01-13T00:05:51.51243Z","shell.execute_reply":"2023-01-13T00:05:51.520902Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**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":"plt.plot(time,signal)","metadata":{"execution":{"iopub.status.busy":"2023-01-13T00:05:53.439434Z","iopub.execute_input":"2023-01-13T00:05:53.439757Z","iopub.status.idle":"2023-01-13T00:05:53.581669Z","shell.execute_reply.started":"2023-01-13T00:05:53.439725Z","shell.execute_reply":"2023-01-13T00:05:53.580697Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels=os.listdir(train_audio_path)     #Extracting labels to determine classes","metadata":{"execution":{"iopub.status.busy":"2023-01-13T00:05:57.801837Z","iopub.execute_input":"2023-01-13T00:05:57.802163Z","iopub.status.idle":"2023-01-13T00:05:57.807104Z","shell.execute_reply.started":"2023-01-13T00:05:57.802134Z","shell.execute_reply":"2023-01-13T00:05:57.806127Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## **Distribution of the Data set**","metadata":{}},{"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":"2023-01-13T00:06:00.778022Z","iopub.execute_input":"2023-01-13T00:06:00.778353Z","iopub.status.idle":"2023-01-13T00:06:01.110199Z","shell.execute_reply.started":"2023-01-13T00:06:00.778315Z","shell.execute_reply":"2023-01-13T00:06:01.109231Z"},"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":"2023-01-13T00:06:04.527084Z","iopub.execute_input":"2023-01-13T00:06:04.527403Z","iopub.status.idle":"2023-01-13T00:06:04.531827Z","shell.execute_reply.started":"2023-01-13T00:06:04.527373Z","shell.execute_reply":"2023-01-13T00:06:04.530735Z"},"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    # sample rate\nvad = malaya_speech.vad.webrtc()\nall_wave = []     #intitialize array to stack wave files of the whole data set in it \nall_label = []    #intitialize array to stack label of wave files of the whole data set in it \nfor label in labels:\n    print(label)\n    waves = [f for f in os.listdir(train_audio_path + '/'+ label) if f.endswith('.wav')] # access on each file\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)  #noise reduction\n        y_= malaya_speech.resample(samples, sr, 16000)               # silence removal\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))     # concatenation with zeros to adust length of the vector\n        all_wave.append(signal)     #append waves one by one \n        all_label.append(label)     #append corresponding label one by one","metadata":{"execution":{"iopub.status.busy":"2023-01-13T00:06:07.354777Z","iopub.execute_input":"2023-01-13T00:06:07.355136Z","iopub.status.idle":"2023-01-13T00:16:06.582595Z","shell.execute_reply.started":"2023-01-13T00:06:07.355103Z","shell.execute_reply":"2023-01-13T00:16:06.581724Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"shape of waves array\",np.array(all_wave).shape)\nprint(\"shape of labels array\",np.array(all_label).shape)\n\n#Inspecting random sample\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":"2023-01-13T00:16:06.584168Z","iopub.execute_input":"2023-01-13T00:16:06.584562Z","iopub.status.idle":"2023-01-13T00:16:18.725576Z","shell.execute_reply.started":"2023-01-13T00:16:06.584514Z","shell.execute_reply":"2023-01-13T00:16:18.724493Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"all_mfcc=[]    #intitialize array to stack MFCCs of the whole data set in it\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)","metadata":{"execution":{"iopub.status.busy":"2023-01-13T00:16:18.727606Z","iopub.execute_input":"2023-01-13T00:16:18.727978Z","iopub.status.idle":"2023-01-13T00:17:37.708079Z","shell.execute_reply.started":"2023-01-13T00:16:18.727941Z","shell.execute_reply":"2023-01-13T00:17:37.706836Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"shape of MFCCs\",np.array(all_mfcc).shape)\nprint(\"shape of Corresponding lables\",np.array(all_label).shape)\n\n# dimensions of the data\nd1=np.array(all_mfcc).shape[1]\nd2=np.array(all_mfcc).shape[2]\nd=d1*d2","metadata":{"execution":{"iopub.status.busy":"2023-01-13T00:17:40.39125Z","iopub.execute_input":"2023-01-13T00:17:40.394414Z","iopub.status.idle":"2023-01-13T00:17:40.962837Z","shell.execute_reply.started":"2023-01-13T00:17:40.394374Z","shell.execute_reply":"2023-01-13T00:17:40.961863Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"op_mfcc=np.array(all_mfcc)\n#op_mfcc=op_mfcc.reshape(np.array(all_mfcc).shape[0],-1)\nop_mfcc.shape","metadata":{"execution":{"iopub.status.busy":"2023-01-13T00:17:42.952654Z","iopub.execute_input":"2023-01-13T00:17:42.953008Z","iopub.status.idle":"2023-01-13T00:17:43.108515Z","shell.execute_reply.started":"2023-01-13T00:17:42.952977Z","shell.execute_reply":"2023-01-13T00:17:43.107605Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Adjusting shape of vector before feeding it to the model \nop_mfcc=op_mfcc.reshape(23666,13,156,-1)\nop_mfcc.shape","metadata":{"execution":{"iopub.status.busy":"2023-01-13T00:17:45.2746Z","iopub.execute_input":"2023-01-13T00:17:45.274952Z","iopub.status.idle":"2023-01-13T00:17:45.280776Z","shell.execute_reply.started":"2023-01-13T00:17:45.274918Z","shell.execute_reply":"2023-01-13T00:17:45.279759Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### One hot encoding","metadata":{}},{"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":"2023-01-13T00:17:49.809453Z","iopub.execute_input":"2023-01-13T00:17:49.809774Z","iopub.status.idle":"2023-01-13T00:17:49.818663Z","shell.execute_reply.started":"2023-01-13T00:17:49.809744Z","shell.execute_reply":"2023-01-13T00:17:49.817823Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## **Model based on CNN** ","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":"2023-01-13T00:17:52.138231Z","iopub.execute_input":"2023-01-13T00:17:52.138541Z","iopub.status.idle":"2023-01-13T00:20:07.87609Z","shell.execute_reply.started":"2023-01-13T00:17:52.138512Z","shell.execute_reply":"2023-01-13T00:20:07.87513Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Importing model libraries from keras\nfrom keras.optimizers import SGD\nfrom keras.constraints import maxnorm\nfrom tensorflow.keras import Sequential\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint\nfrom tensorflow.keras.layers import Dense, Dropout, Flatten, Conv2D, Input, MaxPooling2D\nfrom tensorflow.keras.layers import BatchNormalization","metadata":{"execution":{"iopub.status.busy":"2023-01-13T00:21:06.247682Z","iopub.execute_input":"2023-01-13T00:21:06.248065Z","iopub.status.idle":"2023-01-13T00:21:06.298781Z","shell.execute_reply.started":"2023-01-13T00:21:06.248027Z","shell.execute_reply":"2023-01-13T00:21:06.297727Z"},"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":"2023-01-13T00:21:11.338304Z","iopub.execute_input":"2023-01-13T00:21:11.338628Z","iopub.status.idle":"2023-01-13T00:21:11.347441Z","shell.execute_reply.started":"2023-01-13T00:21:11.338598Z","shell.execute_reply":"2023-01-13T00:21:11.346563Z"},"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":"2023-01-13T00:21:13.261697Z","iopub.execute_input":"2023-01-13T00:21:13.262063Z","iopub.status.idle":"2023-01-13T00:21:13.695679Z","shell.execute_reply.started":"2023-01-13T00:21:13.26203Z","shell.execute_reply":"2023-01-13T00:21:13.694757Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Inspect shapes of each set\nprint(\"shape of training samples\",x_tr.shape)\nprint(\"shape of training labels\",y_tr.shape)\nprint(\"shape of test samples\",x_val.shape)\nprint(\"shape of test labels\",y_val.shape)","metadata":{"execution":{"iopub.status.busy":"2023-01-13T00:21:15.205235Z","iopub.execute_input":"2023-01-13T00:21:15.205758Z","iopub.status.idle":"2023-01-13T00:21:15.214827Z","shell.execute_reply.started":"2023-01-13T00:21:15.20572Z","shell.execute_reply":"2023-01-13T00:21:15.2139Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### **Model Architecture**","metadata":{}},{"cell_type":"code","source":"\n#Model Architecture\nmodel = Sequential()\nmodel.add(Conv2D(32, kernel_size=(4, 4), activation='relu', input_shape=(d1,d2,1)))\nmodel.add(BatchNormalization())\n\nmodel.add(Conv2D(48, kernel_size=(3, 3), activation='relu'))\nmodel.add(BatchNormalization())\n\nmodel.add(Conv2D(120, kernel_size=(3, 3), activation='relu'))\nmodel.add(BatchNormalization())\n\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.5))\n\nmodel.add(Flatten())\n\nmodel.add(Dense(128, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.5))\nmodel.add(Dense(64, activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.5))\nmodel.add(Dense(len(classes), activation='softmax'))","metadata":{"execution":{"iopub.status.busy":"2023-01-13T00:21:17.994952Z","iopub.execute_input":"2023-01-13T00:21:17.995292Z","iopub.status.idle":"2023-01-13T00:21:18.544751Z","shell.execute_reply.started":"2023-01-13T00:21:17.995263Z","shell.execute_reply":"2023-01-13T00:21:18.542756Z"},"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":"2023-01-13T00:21:28.6556Z","iopub.execute_input":"2023-01-13T00:21:28.656094Z","iopub.status.idle":"2023-01-13T00:21:28.683856Z","shell.execute_reply.started":"2023-01-13T00:21:28.656053Z","shell.execute_reply":"2023-01-13T00:21:28.682762Z"},"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-06-25T19:28:46.365188Z","iopub.execute_input":"2022-06-25T19:28:46.3655Z","iopub.status.idle":"2022-06-25T19:28:46.411579Z","shell.execute_reply.started":"2022-06-25T19:28:46.365468Z","shell.execute_reply":"2022-06-25T19:28:46.410656Z"},"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-06-25T19:28:46.41548Z","iopub.execute_input":"2022-06-25T19:28:46.417449Z","iopub.status.idle":"2022-06-25T19:28:46.430639Z","shell.execute_reply.started":"2022-06-25T19:28:46.417412Z","shell.execute_reply":"2022-06-25T19:28:46.42314Z"},"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-06-25T19:28:46.434717Z","iopub.execute_input":"2022-06-25T19:28:46.437684Z","iopub.status.idle":"2022-06-25T19:46:41.171671Z","shell.execute_reply.started":"2022-06-25T19:28:46.437647Z","shell.execute_reply":"2022-06-25T19:46:41.170772Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Model Evaluation","metadata":{}},{"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-06-25T19:46:41.173385Z","iopub.execute_input":"2022-06-25T19:46:41.173824Z","iopub.status.idle":"2022-06-25T19:46:47.029116Z","shell.execute_reply.started":"2022-06-25T19:46:41.173777Z","shell.execute_reply":"2022-06-25T19:46:47.02823Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history.history.keys()","metadata":{"execution":{"iopub.status.busy":"2022-06-25T19:46:47.030456Z","iopub.execute_input":"2022-06-25T19:46:47.030822Z","iopub.status.idle":"2022-06-25T19:46:47.038402Z","shell.execute_reply.started":"2022-06-25T19:46:47.030785Z","shell.execute_reply":"2022-06-25T19:46:47.037488Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(history.history['loss'], label='train')  # losses learning curve of training set.\nplt.plot(history.history['val_loss'], label='test') # losses learning curve of validation set.\nplt.legend()\nplt.title(\"losses learning curves\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-06-25T19:46:47.039876Z","iopub.execute_input":"2022-06-25T19:46:47.040453Z","iopub.status.idle":"2022-06-25T19:46:47.213172Z","shell.execute_reply.started":"2022-06-25T19:46:47.040417Z","shell.execute_reply":"2022-06-25T19:46:47.212354Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(history.history['accuracy'])      # Accuracy learning curve of training set.\nplt.plot(history.history['val_accuracy'])  # Accuracy learning curve of validation set.\nplt.title('model accuracy')\nplt.ylabel('accuracy')\nplt.xlabel('epoch')\nplt.legend(['train', 'val'], loc='upper left')\nplt.title(\"Accuracy learning curves\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-06-25T19:46:47.214501Z","iopub.execute_input":"2022-06-25T19:46:47.215032Z","iopub.status.idle":"2022-06-25T19:46:47.362129Z","shell.execute_reply.started":"2022-06-25T19:46:47.214995Z","shell.execute_reply":"2022-06-25T19:46:47.361383Z"},"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-06-25T19:46:47.363187Z","iopub.execute_input":"2022-06-25T19:46:47.363492Z","iopub.status.idle":"2022-06-25T19:46:48.550604Z","shell.execute_reply.started":"2022-06-25T19:46:47.363467Z","shell.execute_reply":"2022-06-25T19:46:48.549603Z"},"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-06-25T19:46:48.552397Z","iopub.execute_input":"2022-06-25T19:46:48.552967Z","iopub.status.idle":"2022-06-25T19:46:49.405459Z","shell.execute_reply.started":"2022-06-25T19:46:48.552928Z","shell.execute_reply":"2022-06-25T19:46:49.404532Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## loading model to be tested locally.","metadata":{}},{"cell_type":"code","source":"from keras.models import load_model\nmodel.save(\"numbers_cnn.h5\")    ","metadata":{"execution":{"iopub.status.busy":"2022-06-25T19:46:49.510606Z","iopub.status.idle":"2022-06-25T19:46:49.511316Z"},"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":[]}]}