<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kumar Utkarsh on Medium]]></title>
        <description><![CDATA[Stories by Kumar Utkarsh on Medium]]></description>
        <link>https://medium.com/@utkarsh-kumar2407?source=rss-e782653c28f5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*gzo826MgMXrh9GbB</url>
            <title>Stories by Kumar Utkarsh on Medium</title>
            <link>https://medium.com/@utkarsh-kumar2407?source=rss-e782653c28f5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 21:39:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@utkarsh-kumar2407/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Named Entity Recognition using Bidirectional LSTM-CRF]]></title>
            <link>https://utkarsh-kumar2407.medium.com/named-entity-recognition-using-bidirectional-lstm-crf-9f4942746b3c?source=rss-e782653c28f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f4942746b3c</guid>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[language-modeling]]></category>
            <category><![CDATA[long-short-term-memory]]></category>
            <category><![CDATA[named-entity-recognition]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Kumar Utkarsh]]></dc:creator>
            <pubDate>Sun, 15 Mar 2020 18:25:08 GMT</pubDate>
            <atom:updated>2020-03-15T18:25:08.978Z</atom:updated>
            <content:encoded><![CDATA[<p>The objective of this article is to demonstrate how to classify Named Entities in text into a set of predefined classes using <strong>Bidirectional Long Short Term Memory with a Conditional Random Feild</strong>. We are going to implement our model using the Keras library in Python.</p><h3>INTRODUCTION</h3><blockquote><strong>What is a Named Entity and Named Entity Recognition?</strong></blockquote><p>The term <strong>Named Entity</strong> was coined in 1996, at the 6th MUC conference, to refer to <em>“unique identifiers of entities”</em>. In simpler words, a Named Entity is a real-world object like a person, location, organization, etc. that can be denoted with a proper name. Examples of Named Entities are Utkarsh, Taj Mahal, Reliance, etc.</p><p><strong>Named Entity Recognition(NER)</strong> involves the identification of proper names in texts, and the classification of these names into a set of predefined categories of interest like person, location, organization, drug, time, clinical procedure, biological protein, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*kwLyfL3z2RDWRxsyfFM87A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sOmSSDee9LRZLtJl9mUfPQ.jpeg" /></figure><blockquote><strong>Why do we need NER systems?</strong></blockquote><p>Named Entity Recognition(NER) is one of the most common NLP problems and serves as the basis for many areas in Information Management. NER systems find their application in:</p><ul><li>Information Extraction system</li><li>Robust handling of proper names essential for many applications such as Summarization, IR, Anaphora,………</li><li>Pre-processing for different classification levels</li><li>Information filtering</li><li>Information linking</li></ul><h3>DATASET DESCRIPTION</h3><p>GMB(Groningen Meaning Bank) corpus for entity classification can be downloaded from <a href="https://www.kaggle.com/abhinavwalia95/entity-annotated-corpus">here</a>.</p><p>The dataset consists of 4 columns:</p><ul><li>Sentence #</li><li>Word</li><li>POS</li><li>Tag</li></ul><p>Tags of entities are encoded in a BIO-annotation scheme. Each entity is labeled with a B or an I to detect multi-word entities, where B denotes the beginning of an entity and I denote the inside of an entity.</p><p>O denotes all other words which are not named entities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*DnhaSVmGMi0d-FZHqTSnZQ.png" /></figure><p>Having understood what named entity and our task named entity recognition is, we can now dive into coding our deep learning model to perform NER.</p><blockquote><strong><em>Phase 1: Data Reading and Preprocessing</em></strong></blockquote><p><strong>IMPORTING ALL THE LIBRARIES</strong></p><pre># Install extra-dependencies<br>! pip -q install git+<a href="https://www.github.com/keras-team/keras-contrib.git">https://www.github.com/keras-team/keras-contrib.git</a> sklearn-crfsuite</pre><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import tensorflow as tf<br>import keras</pre><p><strong>HYPERPARAMETER INITIALIZATION</strong></p><pre># Hyperparams if GPU is available<br>if tf.test.is_gpu_available():<br>    BATCH_SIZE = 512  # Number of examples used in each iteration<br>    EPOCHS = 5  # Number of passes through entire dataset<br>    MAX_LEN = 75  # Max length of review (in words)<br>    EMBEDDING = 40  # Dimension of word embedding vector</pre><pre># Hyperparams for CPU training<br>else:<br>    BATCH_SIZE = 32<br>    EPOCHS = 5<br>    MAX_LEN = 75<br>    EMBEDDING = 20</pre><p><strong>READING THE DATA</strong></p><pre>data = pd.read_csv(&quot;ner_dataset.csv&quot;, encoding=&quot;latin1&quot;)<br>data = data.fillna(method=&quot;ffill&quot;)</pre><pre>print(&quot;Number of sentences: &quot;, len(data.groupby([&#39;Sentence #&#39;])))</pre><pre>words = list(set(data[&quot;Word&quot;].values))<br>n_words = len(words)<br>print(&quot;Number of words in the dataset: &quot;, n_words)</pre><pre>tags = list(set(data[&quot;Tag&quot;].values))<br>print(&quot;Tags:&quot;, tags)<br>n_tags = len(tags)<br>print(&quot;Number of Labels: &quot;, n_tags)</pre><pre>print(&quot;What the dataset looks like:&quot;)<br># Show the first 10 rows<br>data.head(n=10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*ypwoqG0BSBeDaF4TxIWeBw.png" /><figcaption>OUTPUT</figcaption></figure><p><strong>DATA PREPROCESSING</strong></p><p>The data is then converted into a list of tuples having the format: [(Token_1,PoS_1,Tag_1),…(Token_n,PoS_n,Tag_n)]. The function mentioned below performs the task of converting the data into a list of tuples.</p><pre>class SentenceGetter(object):<br>    &quot;&quot;&quot;Class to Get the sentence in this format:<br>    [(Token_1, Part_of_Speech_1, Tag_1), ..., (Token_n, Part_of_Speech_1, Tag_1)]&quot;&quot;&quot;<br>    def __init__(self, data):<br>        &quot;&quot;&quot;Args:<br>            data is the pandas.DataFrame which contains the above dataset&quot;&quot;&quot;<br>        self.n_sent = 1<br>        self.data = data<br>        self.empty = False<br>        agg_func = lambda s: [(w, p, t) for w, p, t in zip(s[&quot;Word&quot;].values.tolist(),<br>                                                           s[&quot;POS&quot;].values.tolist(),<br>                                                           s[&quot;Tag&quot;].values.tolist())]<br>        self.grouped = self.data.groupby(&quot;Sentence #&quot;).apply(agg_func)<br>        self.sentences = [s for s in self.grouped]<br>    <br>    def get_next(self):<br>        &quot;&quot;&quot;Return one sentence&quot;&quot;&quot;<br>        try:<br>            s = self.grouped[&quot;Sentence: {}&quot;.format(self.n_sent)]<br>            self.n_sent += 1<br>            return s<br>        except:<br>            return None<br>        <br>getter = SentenceGetter(data)<br>sent = getter.get_next()<br>print(&#39;This is what a sentence looks like:&#39;)<br>print(sent)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*-IYXijIsq-7pZnTCnEhD-Q.png" /><figcaption>OUTPUT</figcaption></figure><p><strong>DATA VISUALIZATION</strong></p><p>Now, we’ll try to gain some deeper insight of our dataset. We’ll do this by plotting Number of Samples vs Len(Number of Tokens)</p><pre># Get all the sentences<br>sentences = getter.sentences</pre><pre># Plot sentence by lenght<br>plt.hist([len(s) for s in sentences], bins=50)<br>plt.title(&#39;Token per sentence&#39;)<br>plt.xlabel(&#39;Len (number of token)&#39;)<br>plt.ylabel(&#39;# samples&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*IuqLJE8_TOGdx5_Mvtjrqg.png" /><figcaption>OUTPUT</figcaption></figure><p>It can be clearly observed that the plot of Token per sentence is a <strong>Gaussian Distribution.</strong></p><p><strong>FURTHER DATA PREPROCESSING</strong></p><p>Before feeding the data to the model we need to further preprocess the text.</p><ul><li>We will convert each text word to a corresponding integer ID using the <em>word2idx</em> dictionary. Doing so saves a lot of memory.</li><li>In order to feed the data to out Bi-LSTM-CRF model, we need to ensure that all text should be of the same length. The method <em>sequence.pad_sequences() </em>and variable<em> </em>MAX_LEN<em> </em>are used for this purpose<em>. </em>The text which are shorter than MAX_LEN<em> </em>are padded to get them to the same length, whereas text which are longer than<em> </em>MAX_LEN are truncated<em>.</em></li></ul><p>The <em>Tokens per sentence</em> plot (see above) is useful for setting the MAX_LEN training hyperparameter.</p><pre># Vocabulary Key:word -&gt; Value:token_index<br># The first 2 entries are reserved for PAD and UNK<br>word2idx = {w: i + 2 for i, w in enumerate(words)}<br>word2idx[&quot;UNK&quot;] = 1 # Unknown words<br>word2idx[&quot;PAD&quot;] = 0 # Padding</pre><pre># Vocabulary Key:token_index -&gt; Value:word<br>idx2word = {i: w for w, i in word2idx.items()}</pre><pre># Vocabulary Key:Label/Tag -&gt; Value:tag_index<br># The first entry is reserved for PAD<br>tag2idx = {t: i+1 for i, t in enumerate(tags)}<br>tag2idx[&quot;PAD&quot;] = 0</pre><pre># Vocabulary Key:tag_index -&gt; Value:Label/Tag<br>idx2tag = {i: w for w, i in tag2idx.items()}</pre><pre>print(&quot;The word Obama is identified by the index: {}&quot;.format(word2idx[&quot;Obama&quot;]))<br>print(&quot;The labels B-geo(which defines Geopraphical Enitities) is identified by the index: {}&quot;.format(tag2idx[&quot;B-geo&quot;]))</pre><pre>from keras.preprocessing.sequence import pad_sequences<br># Convert each sentence from list of Token to list of word_index<br>X = [[word2idx[w[0]] for w in s] for s in sentences]<br># Padding each sentence to have the same lenght<br>X = pad_sequences(maxlen=MAX_LEN, sequences=X, padding=&quot;post&quot;, value=word2idx[&quot;PAD&quot;])</pre><pre># Convert Tag/Label to tag_index<br>y = [[tag2idx[w[2]] for w in s] for s in sentences]<br># Padding each sentence to have the same lenght<br>y = pad_sequences(maxlen=MAX_LEN, sequences=y, padding=&quot;post&quot;, value=tag2idx[&quot;PAD&quot;])</pre><pre>from keras.utils import to_categorical<br># One-Hot encode<br>y = [to_categorical(i, num_classes=n_tags+1) for i in y]  # n_tags+1(PAD)</pre><pre>from sklearn.model_selection import train_test_split<br>X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.1)<br>X_tr.shape, X_te.shape, np.array(y_tr).shape, np.array(y_te).shape</pre><pre>print(&#39;Raw Sample: &#39;, &#39; &#39;.join([w[0] for w in sentences[0]]))<br>print(&#39;Raw Label: &#39;, &#39; &#39;.join([w[2] for w in sentences[0]]))<br>print(&#39;After processing, sample:&#39;, X[0])<br>print(&#39;After processing, labels:&#39;, y[0])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*E3ek6qR9rGXITfrpM3ZXfQ.png" /><figcaption>OUTPUT</figcaption></figure><blockquote><strong>Phase 2: Implementing Model Architecture</strong></blockquote><p>Now we are getting into the interesting part which implementing the model to perform Named Entity Recognition. I used Keras library in Python to create the Bi-LSTM-CRF model similar to that of <a href="https://arxiv.org/pdf/1508.01991v1.pdf">Bidirectional LSTM-CRF Models for Sequence Tagging</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*UsnDwWpwK3Ah_FjN1lbs1g.png" /><figcaption>Bi-LSTM-CRF Model as proposed in the Paper.</figcaption></figure><p>Code to define model architecture:</p><pre>from keras.models import Model, Input<br>from keras.layers import LSTM, Embedding, Dense, TimeDistributed, Dropout, Bidirectional<br>from keras_contrib.layers import CRF</pre><pre># Model definition<br>input = Input(shape=(MAX_LEN,))<br>model = Embedding(input_dim=n_words+2, output_dim=EMBEDDING, # n_words + 2 (PAD &amp; UNK)<br>                  input_length=MAX_LEN, mask_zero=True)(input)  # default: 20-dim embedding<br>model = Bidirectional(LSTM(units=50, return_sequences=True,<br>                           recurrent_dropout=0.1))(model)  # variational biLSTM<br>model = TimeDistributed(Dense(50, activation=&quot;relu&quot;))(model)  # a dense layer as suggested by neuralNer<br>crf = CRF(n_tags+1)  # CRF layer, n_tags+1(PAD)<br>out = crf(model)  # output</pre><pre>model = Model(input, out)<br>model.compile(optimizer=&quot;rmsprop&quot;, loss=crf.loss_function, metrics=[crf.accuracy])</pre><pre>model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*zthhR3T1HqrP4rwHmrshtQ.png" /><figcaption>Model Architecture</figcaption></figure><blockquote><strong>Phase 3: Training and Evaluation of the Model</strong></blockquote><p><strong>Training</strong></p><p>After creating the model, I trained the model for 5 epochs on the entire training corpus.</p><pre>history = model.fit(X_tr, np.array(y_tr), batch_size=BATCH_SIZE,            epochs=EPOCHS,validation_split=0.1, verbose=2)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*NxW-aEwOIXJurDyUTNZrAQ.png" /><figcaption>OUTPUT</figcaption></figure><p><em>After running the model for 5 epochs, my model achieved a validation accuracy of </em><strong><em>96.71%. </em></strong><em>The change in model accuracy and loss with respect to the number of epochs can be observed in the visualization given below:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*WK4tg_9_t1K9Gdh388FdAA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*KtSLc5rAqNmXE353erkHeQ.png" /><figcaption>Model Accuracy and Loss Curves</figcaption></figure><p><strong>Evaluation</strong></p><p>For evaluation of the model on this type of task, we should note one thing that Accuracy is not the best metric to measure model performance as the number of class “O” is much more than the number of more important classes. Therefore we have to take other metrics like precision, recall and f1 score into consideration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*JX9TUl9ISIZo7UyCTA5iKQ.png" /><figcaption>Metrics to Evaluate Model Performance</figcaption></figure><p>It is clearly visible that our model can successfully perform the task of Named Entity Recognition.</p><p>We have successfully created a Bidirectional Long Short Term Memory with Conditional Random Feild model to perform Named Entity Recognition using Keras Library in Python.</p><h3>CONCLUSION</h3><p>Named Entity Recognition(NER) finds it’s application in many modern-day applications and real-life situations. It also serves as the basis for many other areas in Information Management. In this article, I have demonstrated how to make your own model to perform NER.</p><p>The entire code can be accessed through my GitHub Repository:</p><p><a href="https://github.com/Utkarsh07/NLP_ASSIGNMENT-NER-Bi-LSTM-CRF">Utkarsh07/NLP_ASSIGNMENT-NER-Bi-LSTM-CRF</a></p><p>This is one of my first articles in the NLP domain. Thank you for reading my article, and I hope you’ve enjoyed reading it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f4942746b3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Wakeup Word Classification]]></title>
            <link>https://utkarsh-kumar2407.medium.com/wakeup-word-classification-d452d4c0ec79?source=rss-e782653c28f5------2</link>
            <guid isPermaLink="false">https://medium.com/p/d452d4c0ec79</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[wake-word]]></category>
            <category><![CDATA[audio-processing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[Kumar Utkarsh]]></dc:creator>
            <pubDate>Sun, 13 Oct 2019 17:38:13 GMT</pubDate>
            <atom:updated>2019-10-13T17:38:13.037Z</atom:updated>
            <content:encoded><![CDATA[<p>The objective of this article is to show how to classify which Wake Word is present in a particular audio signal using various Machine Learning / Deep Learning classification techniques like Neural Network, Logistic Regression, Gradient Boosting, and Support Vector Machine. Later we’ll observe and compare how these different classification models perform on the given task of Wake Word Classification.</p><h3>What is a wake word?</h3><p>Wake word is basically a keyword or phrase which when spoken aloud triggers the interface on a device, typically a smart home’s voice assistant, to listen for user commands or queries and perform specified action accordingly. For example, “Alexa” is the default wake word for Amazon devices such as the Echo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9whWcdzAmCazR3aadtEhJQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*kAphp2_RXwZCfDdkCIr_dg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*ERYqfTAcBs25RkYkgz9FhQ.jpeg" /></figure><h3>DATA SET DESCRIPTION</h3><p>WAKE WORD AUDIO DATA SET SOURCE: <a href="https://github.com/Picovoice/wake-word-benchmark/tree/master/audio">Here</a>.</p><p>A huge shout out to <a href="https://github.com/kenarsa">Alireza Kenarsari</a> for providing the dataset of different Wake Words on GitHub. The dataset consists of 6 directories and each directory has audio files containing that particular wake word.</p><p><strong>WAKE WORD CLASSES:</strong></p><p>The dataset consists of the following 6 classes:</p><p><strong>0: Alexa<br>1:Computer<br>2:Jarvis<br>3:Smart Mirror<br>4:Snowboy<br>5:View Glass</strong></p><p>The entire dataset comprises of 2293 audio files(.wav and .flac)</p><blockquote><strong>Phase 1: Data Reading and Preprocessing</strong></blockquote><p><strong>IMPORTING ALL THE LIBRARIES</strong></p><p>LibROSA is one of the python packages which I have used for music and audio analysis. It provides the building blocks necessary to create music information retrieval systems.</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>import pandas as pd<br>import librosa<br>import librosa.display<br>import os<br>import warnings<br>import IPython.display as ipd<br>warnings.filterwarnings(&#39;ignore&#39;)</pre><p><strong>READING THE DATA</strong></p><pre>folder = os.listdir(&#39;wake-word-benchmark/audio&#39;)</pre><pre>y=[]<br>temp = []<br>data =[]<br>for i in folder:<br>    file=os.listdir(&#39;wake-word-benchmark/audio/&#39;+i)<br>    for j in file:<br>        y.append(i)<br>        x , sr = librosa.load(&#39;wake-word-benchmark/audio/&#39;+i+&#39;/&#39;+j)<br>        data.append(x)<br>    temp.append((librosa.load(&#39;wake-word-benchmark/audio/&#39;+i+&#39;/&#39;+j)))</pre><p><strong>SAMPLE WAVEFORM OF EACH WAKE WORD CLASS</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*LyUtLE_T-QlU46xAFoXjqw.png" /></figure><p>In order to feed the data to any learning algorithm, we first need to extract meaningful features from the given audio signals. Short-Term Fourier Transform (STFT) is one such important feature that can be extracted from audio signals.</p><p><strong>So, What is Short-time Fourier Transform (STFT)?</strong></p><p>Short time Fourier transform (STFT) is one of the methods of linear time-frequency analysis that can provide localized spectrum in time domain by applying Fourier transform in a localized time window. The STFT represents a signal in the time-frequency domain by computing discrete Fourier transforms (DFT) over short overlapping windows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*6ZX427rOKheMEQGSyqTErw.jpeg" /></figure><p><strong>Converting input signals to STFT features</strong></p><pre>Xstft=[]<br>for i in range(len(data)):<br>  Xstft.append(np.abs(librosa.stft(data[i]).mean(axis = 1).T))<br>Xstft=np.array(Xstft)<br>Xstft.shape</pre><pre>##OUTPUT</pre><pre>(2293, 1025)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*pRTqFCbK1CEcdEXrBwhf7w.png" /></figure><p><strong>SAMPLE STFT PLOT OF EACH WAKE WORD CLASS</strong></p><p>Now, we have to convert our target variable i.e. Class Name to One Hot Encoding.</p><h3>What is One Hot Encoding</h3><p><strong>One hot encoding</strong> is a process by which categorical variables are converted into a form that could be provided to ML algorithms to do a better job in prediction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*6R4l16PtM7WXuAiK4hF6sQ.png" /></figure><p><strong>One Hot Encoding the target variable</strong></p><pre>Y = pd.get_dummies(y)<br>Y.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*d8CGmUAzafmmmbYGU4guTw.png" /></figure><p>Once we are done with the preprocessing and everything.</p><p>It’s time for us to get into the exciting part, which is to apply different machine/deep learning algorithms and observe their performance on the preprocessed dataset.</p><blockquote><strong>Phase 2: Trying out different learning algorithms</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*gnaTONVNHrZNY6LsFqjUXw.png" /><figcaption><strong>My Neural Network Architecture</strong></figcaption></figure><h3>1.Neural Network</h3><p>A neural network is a series of algorithms that endeavors to recognize underlying relationships in a set of data through a process that mimics the way the human brain operates. Neural networks can adapt to changing input; so the network generates the best possible result without needing to redesign the output criteria.</p><p>I used Keras library in Python to create an artificial neural network. Keras is a high-level API wrapper for the low-level API, capable of running on top of TensorFlow, CNTK, or Theano.</p><pre>import keras<br>from keras.models import Sequential<br>from keras.layers import Dense, Dropout, Activation<br>from keras.optimizers import SGD<br>from keras import regularizers<br><br><br>model = Sequential()<br>model.add(Dense(256, activation=&#39;relu&#39;, input_dim=1025))<br>model.add(Dropout(0.5))<br>model.add(Dense(128, activation=&#39;relu&#39;))<br>model.add(Dropout(0.5))<br>model.add(Dense(128, activation=&#39;relu&#39;))<br>model.add(Dense(6, activation=&#39;softmax&#39;))<br><br>model.compile(loss=&#39;binary_crossentropy&#39;,<br>              optimizer=&#39;adam&#39;,<br>              metrics=[&#39;accuracy&#39;])<br><br><br>history = model.fit(X_train, y_train, epochs = 25, batch_size = 128, verbose=1,validation_data=(X_test,y_test),shuffle=True)<br><br><br>score = model.evaluate(X_test, y_test, batch_size=128)</pre><pre>##OUTPUT</pre><pre>Train on 1375 samples, validate on 918 samples<br>Epoch 1/25<br>1375/1375 [==============================] - 1s 616us/step - loss: 0.4468 - acc: 0.8333 - val_loss: 0.4372 - val_acc: 0.8333<br>Epoch 2/25<br>1375/1375 [==============================] - 0s 49us/step - loss: 0.4314 - acc: 0.8333 - val_loss: 0.4102 - val_acc: 0.8333<br>Epoch 3/25<br>1375/1375 [==============================] - 0s 53us/step - loss: 0.4079 - acc: 0.8353 - val_loss: 0.3739 - val_acc: 0.8404<br>Epoch 4/25<br>1375/1375 [==============================] - 0s 49us/step - loss: 0.3812 - acc: 0.8407 - val_loss: 0.3429 - val_acc: 0.8551<br>Epoch 5/25<br>1375/1375 [==============================] - 0s 54us/step - loss: 0.3632 - acc: 0.8487 - val_loss: 0.3216 - val_acc: 0.8676<br>Epoch 6/25<br>1375/1375 [==============================] - 0s 54us/step - loss: 0.3414 - acc: 0.8520 - val_loss: 0.3149 - val_acc: 0.8680<br>Epoch 7/25<br>1375/1375 [==============================] - 0s 52us/step - loss: 0.3253 - acc: 0.8581 - val_loss: 0.3003 - val_acc: 0.8787<br>Epoch 8/25<br>1375/1375 [==============================] - 0s 54us/step - loss: 0.3158 - acc: 0.8657 - val_loss: 0.2862 - val_acc: 0.8834<br>Epoch 9/25<br>1375/1375 [==============================] - 0s 52us/step - loss: 0.3033 - acc: 0.8715 - val_loss: 0.2796 - val_acc: 0.8865<br>Epoch 10/25<br>1375/1375 [==============================] - 0s 51us/step - loss: 0.2887 - acc: 0.8768 - val_loss: 0.2647 - val_acc: 0.8932<br>Epoch 11/25<br>1375/1375 [==============================] - 0s 54us/step - loss: 0.2871 - acc: 0.8789 - val_loss: 0.2614 - val_acc: 0.8960<br>Epoch 12/25<br>1375/1375 [==============================] - 0s 52us/step - loss: 0.2690 - acc: 0.8874 - val_loss: 0.2512 - val_acc: 0.8985<br>Epoch 13/25<br>1375/1375 [==============================] - 0s 52us/step - loss: 0.2572 - acc: 0.8910 - val_loss: 0.2446 - val_acc: 0.9018<br>Epoch 14/25<br>1375/1375 [==============================] - 0s 53us/step - loss: 0.2485 - acc: 0.8947 - val_loss: 0.2369 - val_acc: 0.9074<br>Epoch 15/25<br>1375/1375 [==============================] - 0s 52us/step - loss: 0.2364 - acc: 0.8985 - val_loss: 0.2314 - val_acc: 0.9098<br>Epoch 16/25<br>1375/1375 [==============================] - 0s 50us/step - loss: 0.2229 - acc: 0.9072 - val_loss: 0.2242 - val_acc: 0.9101<br>Epoch 17/25<br>1375/1375 [==============================] - 0s 54us/step - loss: 0.2208 - acc: 0.9073 - val_loss: 0.2229 - val_acc: 0.9138<br>Epoch 18/25<br>1375/1375 [==============================] - 0s 57us/step - loss: 0.2135 - acc: 0.9131 - val_loss: 0.2182 - val_acc: 0.9138<br>Epoch 19/25<br>1375/1375 [==============================] - 0s 50us/step - loss: 0.2049 - acc: 0.9170 - val_loss: 0.2160 - val_acc: 0.9172<br>Epoch 20/25<br>1375/1375 [==============================] - 0s 50us/step - loss: 0.1982 - acc: 0.9185 - val_loss: 0.2131 - val_acc: 0.9167<br>Epoch 21/25<br>1375/1375 [==============================] - 0s 51us/step - loss: 0.1923 - acc: 0.9196 - val_loss: 0.2077 - val_acc: 0.9185<br>Epoch 22/25<br>1375/1375 [==============================] - 0s 51us/step - loss: 0.1781 - acc: 0.9273 - val_loss: 0.2015 - val_acc: 0.9216<br>Epoch 23/25<br>1375/1375 [==============================] - 0s 49us/step - loss: 0.1756 - acc: 0.9304 - val_loss: 0.2027 - val_acc: 0.9201<br>Epoch 24/25<br>1375/1375 [==============================] - 0s 50us/step - loss: 0.1672 - acc: 0.9331 - val_loss: 0.2055 - val_acc: 0.9216<br>Epoch 25/25<br>1375/1375 [==============================] - 0s 50us/step - loss: 0.1619 - acc: 0.9354 - val_loss: 0.2068 - val_acc: 0.9203<br>918/918 [==============================] - 0s 15us/step</pre><p><em>After running the model for 25 epochs, my model achieved a validation accuracy of </em><strong><em>92.03%. </em></strong><em>The change in model accuracy and loss with respect to the number of epochs can be observed in the visualization given below:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*CgVDYZz41PCyMgQ4pV-S2A.png" /></figure><p><em>Now experimenting and comparing with other classification models…</em></p><h3>2.Gradient Boosting</h3><p>Gradient boosting is a machine learning technique for regression and classification problems, which produces a prediction model in the form of an ensemble of weak prediction models, typically decision trees. <em>(Wikipedia definition)</em></p><pre>from sklearn.ensemble import GradientBoostingClassifier<br>gb_clf = GradientBoostingClassifier(n_estimators=50, learning_rate=0.5, max_features=3, max_depth=2, random_state=0)<br>gb_clf.fit(X_train, y_train)<br>print(&quot;Learning rate: &quot;, 0.5)<br>print(&quot;Accuracy score (training): {0:.3f}&quot;.format(gb_clf.score(X_train, y_train)))<br>print(&quot;Accuracy score (validation): {0:.3f}&quot;.format(gb_clf.score(X_test, y_test)))</pre><pre>##OUTPUT</pre><pre>Learning rate:  0.5<br>Accuracy score (training): 0.981<br>Accuracy score (validation): 0.715</pre><p>It is visible that on setting the learning rate 0.5, I got a<strong> 98.1%</strong> accuracy on the training set and <strong>71.5% </strong>accuracy on the testing set.</p><p>It is clear that this gradient boosting classifier is overfitting. Overfitting refers to a model that models the training data too well but does not generalize well for new unseen data.</p><p>Overfitting can be addressed but that’s a discussion for another time.</p><h3>3.Logistic Regression</h3><p>Like all regression analyses, logistic regression is a predictive analysis. Logistic regression is used to describe data and to explain the relationship between one dependent binary variable and one or more nominal, ordinal, interval or ratio-level independent variables. Logistic Regression is basically linear regression but with a non-linear sigmoid activation function.</p><pre>from sklearn.datasets import load_iris<br>from sklearn.linear_model import LogisticRegression<br>from sklearn.metrics import accuracy_score<br>clf = LogisticRegression(random_state=0, solver=&#39;lbfgs&#39;,multi_class=&#39;multinomial&#39;,max_iter=1000).fit(X_train,y_train)<br>y_pred = clf.predict(X_test)<br>accuracy_score(y_pred,y_test)</pre><pre>##OUTPUT</pre><pre>0.673202614379085</pre><p><em>Using Logistic Regression I was able to get a classification accuracy of around</em><strong><em> 67.32%</em></strong><em> on the validation set.</em></p><h3>4.CART</h3><p>Classification and Regression Trees or CART for short is a term introduced by Leo Breiman to refer to Decision Tree algorithms that can be used for classification or regression predictive modeling problems. Classically, this algorithm is referred to as “decision trees”, but on some platforms like R they are referred to by the more modern term CART. The CART algorithm provides a foundation for important algorithms like bagged decision trees, random forest and boosted decision trees</p><pre>from sklearn.tree import DecisionTreeClassifier<br>decision_tree = DecisionTreeClassifier(random_state=0)<br>decision_tree = decision_tree.fit(X_train,y_train)<br>y_pred = decision_tree.predict(X_test)<br>accuracy_score(y_pred,y_test)</pre><pre>##OUTPUT</pre><pre>0.5915032679738562</pre><p><em>Using CART I was able to get an accuracy of</em><strong><em> 59.15%.</em></strong></p><h3>4.SVM</h3><p>SVM or Support Vector Machine is a linear model for classification and regression problems. It can solve linear and non-linear problems and work well for many practical problems. The idea of SVM is simple: The algorithm creates a line or a hyperplane which separates the data into classes. It is a large margin classifier i.e. it tries to separate data with as large margin as possible</p><pre>from sklearn import svm<br>clf = svm.LinearSVC()<br>clf.fit(X_train,y_train) <br>y_pred = clf.predict(X_test)<br>accuracy_score(y_pred,y_test)</pre><pre>##OUTPUT</pre><pre>0.6470588235294118</pre><p><em>And finally using Support Vector Machines (SVM), I was able to get a validation accuracy of </em><strong><em>64.70%</em></strong></p><h3><strong>Conclusion</strong></h3><p>As it can be observed that our Neural Network performs much better than any other classical machine learning approaches like Logistic Regression, CART and Gradient Boosting. This is because Neural Networks are capable of extracting complex relationships in data and model non-linear decision boundaries using non-linear activation functions.</p><p>The entire code can be accessed through my GitHub Repository:</p><p><a href="https://github.com/Utkarsh07/Home-Assignment-Wake-Word-Detetction.git">Utkarsh07/Home-Assignment-Wake-Word-Detetction</a></p><p>This is one of my first applications in machine learning. Thank you for reading my article, and I hope you’ve enjoyed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d452d4c0ec79" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>