<?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 Rishang Prashnani on Medium]]></title>
        <description><![CDATA[Stories by Rishang Prashnani on Medium]]></description>
        <link>https://medium.com/@p-rishang007?source=rss-b43b4573bdb6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*T9FVxs4m3UWpSNKGIJa7zA.jpeg</url>
            <title>Stories by Rishang Prashnani on Medium</title>
            <link>https://medium.com/@p-rishang007?source=rss-b43b4573bdb6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 00:25:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@p-rishang007/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[Deep Text Corrector using Monotonic Attention (with dataset creation)]]></title>
            <link>https://medium.com/data-science/deep-text-corrector-using-monotonic-attention-with-dataset-creation-1e1a3f5a1b9e?source=rss-b43b4573bdb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e1a3f5a1b9e</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[attention]]></category>
            <dc:creator><![CDATA[Rishang Prashnani]]></dc:creator>
            <pubDate>Sun, 28 Mar 2021 11:06:09 GMT</pubDate>
            <atom:updated>2021-07-02T03:42:56.640Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deep Learning Text Corrector using Monotonic Attention (with dataset creation)</h3><h4>Deep Learning Model to correct a sentence grammatically. Uses Seq2Seq model with Monotonic Attention.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pwnVXFO3Nk7Yl3VaFbklIQ.jpeg" /><figcaption>Image <a href="https://www.123rf.com/photo_84772415_english-sentences-with-red-pen-for-proofreading.html">credits</a></figcaption></figure><h3>Table of Contents</h3><ol><li><strong>Introduction</strong></li><li><strong>Dataset creation</strong></li><li><strong>Attention mechanism</strong></li><li><strong>Monotonic attention</strong></li><li><strong>Implementation and Code Walkthrough</strong></li><li><strong>Inference → Beam Search v/s Greedy Search</strong></li><li><strong>Results and Error Analysis</strong></li><li><strong>End to End Pipeline</strong></li></ol><h3>Introduction</h3><p>Sequence-to-Sequence models are proving to be one of the best applications of Artificial Intelligence in the field of Natural Language Processing. Attention mechanism has improved the seq2seq models a lot by a simple concept of mimicking the human way of understanding a sentence.</p><blockquote>In this blog, I have build a machine learning model which corrects basic grammatical mistakes in a sentence using M<strong>onotonic Attention</strong>.</blockquote><p><strong>Some of the perturbations addressed by my model are-</strong></p><ol><li>Correcting the mistake of using determiners (a, an, the).</li><li>Removing subordinate clause — “that”.</li><li>Replacing word modal (‘may’ → ‘would’)</li><li>Removing verb forms (‘is’, ‘are’, ‘was’, ‘were’)</li><li>Replacing “than” with “then” and vice-versa.</li><li>Replacing “he/she” with “they”.</li></ol><h3>Creating Dataset for this case study</h3><p>For this project, along with the movie corpus dataset (<a href="https://www.cs.cornell.edu/~cristian/Cornell_Movie-Dialogs_Corpus.html">Cornell Movie Dialogue Corpus</a>), I have created a dataset from scratch. I have used Harry Potter novel as my raw data. The text preprocessing has been done using Regular Expressions. <strong>After looking through the discrepancies in the data, these are the preprocessing steps I have undertaken. Some of them are-</strong></p><ol><li><strong>Removing dot from Mr and Mrs- </strong>This step is required to make sure that the paragraph is sliced into sentences correctly. (Point-4)</li></ol><pre>xx_v2 = re.sub(r&#39;Mr\.&#39;, &#39;Mr&#39;, str(xx), flags=re.IGNORECASE)</pre><pre>xx_v2 = re.sub(r&#39;Mrs\.&#39;, &#39;Mrs&#39;, xx_v2, flags=re.IGNORECASE)</pre><p><strong>2. Removing some special characters- </strong>When the book was converted from pdf to txt, some of the special symbols changed into a text code like —</p><p>\xe2\x80\x94 → “ — “<br>\xe2\x80\x99 → “ ‘ “<br>\xe2\x80\xa6 → “ … “</p><p>So, these were detected and removed using regular expressions.</p><pre>xx_v3 = re.sub(r&quot;\\xe2\\x80\\x94|\\xe2\\x80\\xa6|\\xe2\\x80\\x98|\\n|\\t&quot;,  &quot; &quot;, xx_v2, flags=re.IGNORECASE)</pre><p><strong>3.</strong> <strong>Repairing the data- </strong>A novel contains a lot of quoted text said by different characters. They were also converted to some text-code while converting the pdf to text. These were then detected and replaced to their original form i.e<br>\\xe2\x80\x9c → “<br>\\xe2\x80\x9d → ”</p><pre>xx_v4 = re.sub(r&quot;\\xe2\\x80\\x9c&quot;, &#39;&quot;&#39;, xx_v3, flags=re.IGNORECASE)</pre><pre>xx_v4 = re.sub(r&quot;\\xe2\\x80\\x9d&quot;, &#39;&quot;&#39;, xx_v4, flags=re.IGNORECASE)</pre><p><strong>4. Splitting the data on full stop- </strong>Converting the data into sentences.</p><pre>dat_v4 = xx_v4.split(&quot;.&quot;)</pre><p><strong>5. Final Step- Extracting the sentences</strong></p><p>→In a novel, there are a lot of instances when a character says something which is written in the quoted text followed by this sentence “ said the character”.<br><strong>For example → “I am going” said Harry.</strong><br>These type of sentence needs to be removed because they are half-sentences.</p><p>So, we removed these half-sentences by identifying the words like — ‘said’, ‘whispered’, ‘asked’ etc ***</p><p>→Lastly, after this also, some <strong>sentences are questions</strong>. So, we again split it with <strong>.split(“?”)</strong> but retain the question mark to make sure <strong>our model understands the difference between an affirmative sentence and a question.</strong></p><p><strong>***Note- Also if there were full sentences inside a quote, they are already split correctly in step-4.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17f7d71932e70929d09688011f730681/href">https://medium.com/media/17f7d71932e70929d09688011f730681/href</a></iframe><blockquote><strong>We do a similar preprocessing of the movie corpus dataset as well.</strong></blockquote><h3>Attention Mechanism Overview</h3><p>Note: Assuming that the reader is versed with attention, I will only give an overview of the attention mechanism. Please read <a href="https://towardsdatascience.com/intuitive-understanding-of-attention-mechanism-in-deep-learning-6c9482aecf4f"><strong>this</strong></a> really nice blog by <a href="https://medium.com/u/a35dfc76e885">Harshall Lamba</a> if you are new to attention.</p><h4>Overview</h4><p>The name ‘attention’ itself gives us an idea of what this algorithm does. In an ordinary Encoder-Decoder Model, all the intermediate states of the encoder are discarded and the final state is used as the initial state for the decoder. The idea behind is simple- the final state contains all the information of the input sentence which can be used by a decoder to predict the output. But, when the sequence is long it’s hard for this model to encode all the information in one vector.</p><p>Whereas in the attention mechanism, we try to mimic how humans process sequential information. We do this by giving weight to each word (encoder intermediate states) thus giving <strong>attention</strong> to a particular word for a particular prediction. This is implemented through a feed-forward neural network which takes all the intermediate state of the encoder as input along with the previous decoder state and gives out the weight of each word for that <strong>timestamp</strong>.</p><h3>Monotonic Attention</h3><p>In Attention, at every timestamp, we calculate the weights of all the words to make sure that we are not ruling out the possibility of say- <strong>1st word influencing prediction of 3rd word or say last word influencing 1st prediction.</strong> In other words, the attention <strong>independently</strong> considers all the intermediate states, and thus, the output of that timestamp can depend on any input word (means any word can have more weight)</p><p>This figure depicts the attention model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/0*5Frzl4RBbQfv-K8P.png" /><figcaption>Attention Mechanism Weights Map</figcaption></figure><blockquote><strong><em>Output can depend on any word for its prediction</em></strong></blockquote><p><strong><em>But in the case of Monotonic Attention, instead of inspecting all entries of the memory independently and choosing one, we start inspecting entries from where we left off at the previous output timestep and explicitly process them in a left-to-right manner.</em></strong></p><p>That is, once an input sequence element is attended to at a given output timestep, elements occurring before it cannot be attended to at subsequent output timesteps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/0*rwJrHSSy3xvnqo9o.png" /><figcaption>Monotonic Attention Weights Map</figcaption></figure><p>As we can see clearly from the figure, the 1st output is dependent on the 1st word and hence the 2nd output cannot use the first word and uses the 2nd and 3rd word for its prediction. It goes on strictly from left-to-right.</p><blockquote>In Monotonic Attention, the only words which have not been used by previous outputs can have effect on the present output and it’s strictly left to right</blockquote><blockquote><strong>This makes the model less complex and has particularly helped me in this case study where it performed far better than Attention.</strong></blockquote><h3>Implementation and Code Walkthrough</h3><p>Let us implement monotonic attention on the dataset and create a text corrector model.</p><h4><strong>We will start with the basic preprocessing of our dataset</strong></h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b2b0e75a0714233d0fd40d46206db44/href">https://medium.com/media/0b2b0e75a0714233d0fd40d46206db44/href</a></iframe><p><strong>Now its time to add some perturbations</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fff96dfb88cf2ebf46226da5851631d9/href">https://medium.com/media/fff96dfb88cf2ebf46226da5851631d9/href</a></iframe><h4><strong>Creating input-output pair for encoder-decoder with teacher forcing*.</strong></h4><p>Teacher forcing is a method where we explicitly give <strong>input</strong> to the decoder instead of passing the <strong>output of the decoder </strong>to the next timestamp. This is obviously only used during training and helps reduce training time and improves accuracy.</p><pre>dataframe[&#39;decoder_input&#39;] = &#39;&lt;start&gt; &#39; + dataframe[&#39;output&#39;].astype(str)</pre><pre>dataframe[&#39;decoder_output&#39;] = dataframe[&#39;output&#39;].astype(str) + &#39; &lt;end&gt;&#39;</pre><pre>dataframe = dataframe.drop([&#39;output&#39;], axis=1)</pre><p><strong>Example-</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FfqYh3hUSsZuP9RikTL3zA.png" /><figcaption>‘a’ is missing for the encoder input</figcaption></figure><p>→ <strong>After this, we split the dataset into train, validation, and test.</strong></p><p>→ <strong>Then we tokenize the data which converts the word into integer tokens to train the model.</strong></p><h4><strong>Embedding matrix for pre-trained vectors-</strong></h4><p>After tokenizing the data, we create embedding_matrix which contains pre-trained embedding vectors for our words using GLOVE-300 pre-trained vectors for both our correct_tokens and perturbated_tokens.</p><p>Embedding matrix for correct_tokens</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0665ed213e4f0d1b1e3cc3c5831ade17/href">https://medium.com/media/0665ed213e4f0d1b1e3cc3c5831ade17/href</a></iframe><h4><strong>Implementing our deep text corrector model</strong></h4><p>After all the preprocessing and creating the embedding matrix, we are ready to create our <strong>Encoder-Decoder Model with Monotonic Attention.</strong></p><p><strong>We will use the method of Model subclassing deriving our model from Keras’ Model and Layer class.</strong></p><p><strong>The Encoder Model is implemented below-</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c97e4b042212da1af9b1a204488a01ad/href">https://medium.com/media/c97e4b042212da1af9b1a204488a01ad/href</a></iframe><blockquote><strong>After this we create → monotonic attention layer, OneStep Decoder Layer, Decoder Model and the final model which contains Encoder and Decoder.</strong></blockquote><h4>For full details of my implementation, check my <a href="https://github.com/Rishang007">Github profile</a></h4><h4>Data Pipeline</h4><p>Now we need something which can take our data, convert it into batches of data into the required dimensions. For this, we create a data pipeline by deriving from the Keras’ Sequence layer</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da855871a33ed4b525d1237d01e903bd/href">https://medium.com/media/da855871a33ed4b525d1237d01e903bd/href</a></iframe><h4>Training</h4><p>It&#39;s time we train our model, finally!</p><p>We are training on ‘ADAM’ optimizer and a custom loss function which makes sure that we do not calculate the loss for padded values since we have heavily padded the data.</p><pre>train_steps=train.shape[0]//512</pre><pre>valid_steps=validation.shape[0]//512</pre><pre>attention__.fit(train_dataloader, steps_per_epoch=train_steps, epochs=120, validation_data=validation_dataloader, callbacks=[es,chkpt,tfboard], validation_steps=valid_steps, )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o0Qb5e6qkFF5et7Ujxgn8w.png" /><figcaption>Training Plot (Blue-&gt; Validation)</figcaption></figure><h3>Inference</h3><p>After training the model, it is time we check its efficiency. <strong>We will use BLEU Score as our metric.</strong></p><h4><strong>Greedy Search v/s Beam Search</strong></h4><p>We are using two types of search to predict our output.</p><p><strong>Spoiler Alert!!! → </strong>Both of them performed similarly, hence I end up using Greedy Search.</p><p><strong>Greedy Search →</strong></p><p>The model’s output is a huge probability table containing the probability of our word from the vocabulary. In Greedy search, we just simply choose the word with the highest probability.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd7d29f01f5812475727a55d61074016/href">https://medium.com/media/fd7d29f01f5812475727a55d61074016/href</a></iframe><h4>Beam Search</h4><p>In beam search algorithm, instead of choosing a word with the highest probability, we choose the top 3 words (beam_index=3). Based on these top 3 words, we predict the next word and calculate the conditional probability of these words with our previous words. This process is carried on till we reach the end.</p><blockquote><strong><em>To understand BEAM Search properly, watch this </em></strong><a href="https://www.youtube.com/watch?v=RLWuzLLSIgw"><strong><em>video</em></strong></a><strong><em> by Andrew Ng and read this </em></strong><a href="https://medium.com/@dhartidhami/beam-search-in-seq2seq-model-7606d55b21a5"><strong><em>article</em></strong></a><strong><em> by </em></strong><a href="https://medium.com/u/adb57bd98a88"><strong><em>Dharti Dhami</em></strong></a></blockquote><p><strong>Implementation of Beam Search with Beam index = 3</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ef97187c6b0e12d074aabc486a038ee/href">https://medium.com/media/7ef97187c6b0e12d074aabc486a038ee/href</a></iframe><h3><strong>Results and Error Analysis</strong></h3><p>With normal attention, I was getting around <strong>0.90</strong> BLEU Score for the training dataset while <strong>0.75</strong> BLEU Score for validation and test dataset.</p><p>But with Monotonic Attention, I am getting a <strong>0.98</strong> BLEU Score for the training dataset while a BLEU Score of <strong>0.90</strong> for the test and validation dataset. <strong>This is a significant improvement!</strong></p><h4>Error Analysis</h4><p>I analyzed the errors and found the following problems with our model which could be the cause of <strong>missing 0.10</strong> from our score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*INHro5R4nBxCWiJG4TY00Q.png" /><figcaption>1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YkreXCyUC22C7KdF-j1mUw.png" /><figcaption>2</figcaption></figure><h3>End to End Pipeline</h3><p>In the last phase of this project, I created an End to End pipeline for deployment which takes the input and predicts the output, and can be directly used for any application.</p><p><strong>First, I created a module (.py file) named monotonic_attention which contains our Encoder-Decoder model.</strong></p><p><strong>Then, I created another module named model.py which imports the above module and predicts the output. It contains a method predict() which performs inference with greedy search</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jFGqric06wklemJApoz2LA.png" /><figcaption>After importing, we initialize our model with all the files and a model_weight</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1c3_2cBIogP0L5_lIdCTCw.png" /><figcaption>Predicting</figcaption></figure><p>If you have reached this far. Wow, !THANKYOU! for reading my article. I hope you did not skip to here directly! ;)</p><h3>References</h3><ol><li><strong>Monotonic Attention Paper — </strong><a href="https://colinraffel.com/blog/online-and-linear-time-attention-by-enforcing-monotonic-alignments.html">https://colinraffel.com/blog/online-and-linear-time-attention-by-enforcing-monotonic-alignments.html</a></li><li><a href="https://github.com/UdiBhaskar/TfKeras-Custom-Layers/blob/master/Seq2Seq/clayers.py">https://github.com/UdiBhaskar/TfKeras-Custom-Layers/blob/master/Seq2Seq/clayers.py</a></li><li><a href="https://appliedaicourse-1.medium.com/faqs-about-attention-assignment-3033ac9f05ac">https://appliedaicourse-1.medium.com/faqs-about-attention-assignment-3033ac9f05ac</a></li><li><strong>Project done under the guidance of Uday Paila at AppliedAI course.</strong> <a href="https://www.appliedaicourse.com/">https://www.appliedaicourse.com/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e1a3f5a1b9e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/deep-text-corrector-using-monotonic-attention-with-dataset-creation-1e1a3f5a1b9e">Deep Text Corrector using Monotonic Attention (with dataset creation)</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I preprocessed text data using Regular Expressions for my Text classification task (CNN)]]></title>
            <link>https://medium.com/data-science/how-i-preprocessed-text-data-using-regular-expressions-for-my-text-classification-task-cnn-cb206e7274ed?source=rss-b43b4573bdb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb206e7274ed</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[regex]]></category>
            <category><![CDATA[text-classification]]></category>
            <dc:creator><![CDATA[Rishang Prashnani]]></dc:creator>
            <pubDate>Sat, 20 Jun 2020 14:05:21 GMT</pubDate>
            <atom:updated>2021-04-07T07:08:31.273Z</atom:updated>
            <content:encoded><![CDATA[<h3>How I preprocessed text data with Regular Expressions for my Text classification task using CNN</h3><h3>Steps undertaken during preprocessing using regex</h3><ol><li>Extracting label and document no. from filename</li><li>Extracting Email</li><li>Extracting Subject</li><li>Decontractions</li><li>Removing Write to: , From: , or:</li><li>Removing data within brackets &lt;&gt; , ()</li><li>Removing newlines, tabs</li><li>Preprocessing person and city name with <strong>Chunking</strong></li><li>Removing digits</li><li>Replacing “_word_” , “_word” , “word_” to word using <strong>Match Captures</strong></li><li>Miscellaneous</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wf89DaXXNLF5xCr-rhwOzQ.png" /></figure><h3>Introduction</h3><p>Natural language processing is a branch of AI which deals with language data. It basically is a branch where interaction between humans and achine is researched. Machine translation, text to speech, text classification — these are some of the applications of Natural Language Processing.</p><blockquote>In this article, I am going to classify text data using 1D Convolutional Neural Network extensively using Regular Expressions for string preprocessing and filtering.</blockquote><blockquote><strong>Our focus on this article is how to use regex for text data preprocessing</strong></blockquote><h3>Problem Statement</h3><p>The data is <strong>Newsgroup20 </strong>dataset. There are total 20 types of documents in our data. The name of the document contains the label and the number in that label. The format is <strong>‘ClassLabel_DocumentNumberInThatLabel’. </strong>The data can be downloaded from <a href="https://drive.google.com/file/d/1rxD15nyeIPIAZ-J2VYPrDRZI66-TBWvM/view">here</a>.</p><p>Our task is to preprocess the text data and classify it into a correct label.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3PBD8-nGd_VYZTf8hrdYVw.png" /><figcaption>Count plot of the class labels</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j3kh0ToZpAenpxWXkUkoZw.png" /><figcaption>Example Data (We will follow this data throughout the article)</figcaption></figure><h3>Preprocessing using Regex</h3><p>We have created a single function which takes raw data as input and gives preprocessed filtered data as output.</p><h4>I. Extracting label and document no. from filename</h4><p>We will use split method which applies on strings.</p><pre>1   for filename in os.listdir(path):<br>2       i,j = filename.split(&#39;_&#39;)<br>3       j = int(j.split(&#39;.&#39;)[0])<br>4       label.append(i) <br>5       doc_num.append(j)</pre><p>For all the filenames in the path, we take the filename and split it on ‘_’. <strong>The function .split() uses the element inside the paranthesis to split the string.</strong> Similarly we use it again to filter the <strong>.txt</strong> in filename.</p><pre><strong>Ex.- we get i = talk.religion.misc and j = 82778</strong></pre><h4><strong>II. Extracting Email</strong></h4><p>Our task is to find all the emails in a document, take the text after “@” and split it with “.” , remove all the words less than 3 and remove “.com” . Combine all in a single string. Then finally we remove the email from our text.</p><pre>Ex.-<br><strong>[bskendig@netcom.com , joslin@pogo.isp.pitt.edu] → </strong></pre><pre><strong>[netcom, pogo.isp.pitt.edu] → [netcom, pogo, isp, pitt, edu] →</strong></pre><pre><strong>“netcom pogo isp pitt edu”</strong></pre><p>Following code executes the task</p><pre>em = [] # for each doc<br>st = &quot;&quot;  # for each doc</pre><pre>#extracting email<br>for i in re.findall(r&#39;[\w\-\.]+@[\w\.-]+\b&#39;, f):  #extracting email <br>    temp=[]<br>    temp = i.split(&#39;@&#39;)[1]      #taking text after @<br>    temp = temp.split(&#39;.&#39;)     #a list containing words split by &quot;.&quot;</pre><pre>    if &#39;com&#39; in temp:<br>        temp.remove(&#39;com&#39;)<br> <br>   for i in temp:            #removing words less than 3<br>        if len(i)&gt;2:<br>            em.append(i)</pre><pre>for i in em:            #joining all the words in a string<br>    st+=i<br>    st+=&#39; &#39;</pre><pre>re.sub(r&#39;[\w\-\.]+@[\w\.-]+\b&#39;,&#39; &#39;)    #removing the email</pre><p><strong>REGEX Explanation</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*kN45MYnJ9fApflJpHN-QOg.png" /></figure><p><strong>\w → </strong>Match any alphanumeric character</p><p><strong>\-\. → </strong>Match “-” and “.” ( “\” is used to escape special characters)</p><p><strong>[]+ → </strong>Match one or more than one characters inside the brackets</p><p><strong>………………………………………………. @ → </strong>Match “@” after [\w\-\.]</p><h4>III Extracting Subject</h4><p>In this task, we are going to keep only the useful information from the subject section. <strong>Subject: </strong>will be removed and all the non-alphanumeric characters will be removed. The following code executes the task-</p><pre>#extracting subject<br>temp1 = re.findall(r&#39;^Subject.*$&#39;,f, re.MULTILINE)</pre><pre>sub = temp1[0]<br>sub = sub[7:]   #Truncate Subject</pre><pre>for i in string.punctuation:   #remove all the non-alphanumeric<br>    sub = sub.replace(i,&quot; &quot;)</pre><pre>    sub = re.sub(r&quot;re&quot;,&quot;&quot;,sub, flags=re.IGNORECASE) #removing Re</pre><pre>    sub = sub.lower()  #lower-casing</pre><pre>re.sub(r&#39;Subject.*$&#39;,&quot; &quot;, flags=re.MULTILINE)  #removing subject</pre><p><strong>REGEX Explanation</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YCpj-ljVAvrIb8y4rOscqw.png" /></figure><p><strong>^ → </strong>Accounts for the beginning of the string.</p><p><strong>Subject → </strong>To match that the beginning of the string is the word Subject.</p><p><strong>.*</strong> → Matches 0 or more words after Subject.</p><p><strong>$</strong> → To detect the end of string.</p><p><strong>Note: </strong>“<strong>^</strong>” is important to ensure that Regex detects the ‘Subject’ of the heading only. It should not detect the word ‘subject’ in any other part of our text.</p><h4>IV. Decontractions</h4><p>Replacing the words like <strong>I’ll with I will</strong>, <strong>can’t with cannot</strong> etc..</p><pre># specific<br>f = re.sub(r&quot;won&#39;t&quot;, &quot;will not&quot;, f)<br>f = re.sub(r&quot;can\&#39;t&quot;, &quot;can not&quot;, f)</pre><pre># general<br>f = re.sub(r&quot;n\&#39;t&quot;, &quot; not&quot;, f)<br>f = re.sub(r&quot;\&#39;re&quot;, &quot; are&quot;, f)<br>f = re.sub(r&quot;\&#39;s&quot;, &quot; is&quot;, f)<br>f = re.sub(r&quot;\&#39;d&quot;, &quot; would&quot;, f)<br>f = re.sub(r&quot;\&#39;ll&quot;, &quot; will&quot;, f)<br>f = re.sub(r&quot;\&#39;t&quot;, &quot; not&quot;, f)<br>f = re.sub(r&quot;\&#39;ve&quot;, &quot; have&quot;, f)<br>f = re.sub(r&quot;\&#39;m&quot;, &quot; am&quot;, f)</pre><h4>V. Removing Write to: , From: , or:</h4><p>Removing the content like addresses which are written under “write to:”, “From:” and “or:” .</p><pre>f = re.sub(r&quot;Write to:.*$&quot;,&quot;&quot;,f, flags=re.MULTILINE)           </pre><pre>f = re.sub(r&quot;From:.*$&quot;,&quot;&quot;,f, flags=re.MULTILINE)               </pre><pre>f = re.sub(r&quot;or:&quot;,&quot;&quot;,f,flags=re.MULTILINE)</pre><p><strong>Note- “$”</strong> matches the end of string just for safety</p><h4><strong>VI. Removing data within brackets &lt;&gt; , ()</strong></h4><p>Deleting all the data which is inside the brackets.</p><p>Eg- My name is Ramesh (chintu) → My name is Ramesh</p><pre>f = re.sub(r&quot;&lt;.*&gt;&quot;,&quot;&quot;,f, flags=re.MULTILINE) </pre><pre>f = re.sub(r&quot;\(.*\)&quot;,&quot;&quot;,f,flags=re.MULTILINE)                 </pre><h4><strong>VII. Removing newlines, tabs</strong></h4><pre>#delete /,-,/n,</pre><pre>f = re.sub(r&quot;[\n\t\-\\\/]&quot;,&quot; &quot;,f, flags=re.MULTILINE)</pre><h4>VIII. Chunking</h4><p>Chunking is the process of extracting valuable phrases from sentences based on Part-of-Speech tagging. It adds more strcuture to the sentence and helps machine understand the meaning of sentence more accurately. You can read this <a href="https://towardsdatascience.com/chunking-in-nlp-decoded-b4a71b2b4e24">article</a> by <a href="https://medium.com/u/e44ae4099762">Nikita Bachani</a> where she has explained chunking in detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aLn-2hkpbJBS5WCCORKoJA.png" /><figcaption>Example of Chunking</figcaption></figure><p><strong>Our task</strong> here is to remove names and add underscore to city names with the help of Chunking. Ex- Ramesh will be removed and New Delhi → New_Delhi</p><pre>chunks=[]<br>chunks=(list(ne_chunk(pos_tag(word_tokenize(f)))))</pre><pre>for i in chunks:<br>    if type(i)==Tree:<br>        if i.label() == &quot;GPE&quot;:<br>            j = i.leaves()<br>                if len(j)&gt;1:   #if new_delhi or bigger name<br>                    gpe = &quot;_&quot;.join([term for term,pos in j])</pre><pre>                    f = re.sub(rf&#39;{j[1][0]}&#39;,gpe,f, flags=re.MULTILINE)              #replacing delhi with new_delhi<br></pre><pre>                    f = re.sub(rf&#39;\b{j[0][0]}\b&#39;,&quot;&quot;,f, flags=re.MULTILINE)       #deleting new, \b is important</pre><pre>        if i.label()==&quot;PERSON&quot;:           # deleting Ramesh         <br>            for term,pog in i.leaves():<br>                f = re.sub(re.escape(term),&quot;&quot;,f, flags=re.MULTILINE)</pre><p>As we can see above, chunks has three parts- <strong>label, term, pos. </strong>If the type is tree and label is GPE, then its a place. If the place hasmore than one word, we join them using “_”.</p><pre>f = re.sub(rf&#39;{j[1][0]}&#39;,gpe,f, flags=re.MULTILINE)<br>f = re.sub(rf&#39;\b{j[0][0]}\b&#39;,&quot;&quot;,f, flags=re.MULTILINE)</pre><p>We used format string and regex together. “j” contains leaf, hence j[1][0] contains the second term i.e <strong>Delhi </strong>and j[0][0] contains the first term i.e <strong>New. So, we replaced delhi with new_delhi and deleted new. \b is to detect the end of the word.</strong></p><pre>f = re.sub(re.escape(term),&quot;&quot;,f, flags=re.MULTILINE)</pre><p>To delete Person, we use <strong>re.escape</strong> because the term can contain a character which is a special character for regex but we want to treat it as just a string.</p><h4>IX. Removing digits</h4><pre>f = re.sub(r&#39;\d&#39;,&quot;&quot;,f, flags=re.MULTILINE)                               </pre><h4>X. Replacing “_word_” , “_word” , “word_” to word</h4><pre>f = re.sub(r&quot;\b_([a-zA-z]+)_\b&quot;,r&quot;\1&quot;,f) #replace _word_ to word<br>   <br>f = re.sub(r&quot;\b_([a-zA-z]+)\b&quot;,r&quot;\1&quot;,f) #replace_word to word</pre><pre>f = re.sub(r&quot;\b([a-zA-z]+)_\b&quot;,r&quot;\1&quot;,f) #replace word_ to word</pre><p>Here, we use something called as <strong>Match Captures.</strong></p><p>After we get our string _word_ using “<strong>\b_([a-zA-z]+)_\b”, </strong>match captures enable us to just use a specific part of the matched string. Here we have one group in paranthesis in between the underscores. Hence we have 1 group here. We use <strong>r ‘\1’</strong> to extract the particular group. Simple example to explain the concept.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iQcidgG2Nm9HhfkrZAdMkw.png" /><figcaption>There are two paranthesis, so there are two match captures</figcaption></figure><h4>XI Miscellaneous</h4><p>{m,n} → This is used to match number of characters between m and n. m can be zero and n can be infinity.</p><pre>f = re.sub(r&quot;\b[a-zA-Z]{1}_([a-zA-Z]+)&quot;,r&quot;\1&quot;,f) #d_berlin to berlin</pre><pre>f = re.sub(r&quot;\b[a-zA-Z]{2}_([a-zA-Z]+)&quot;,r&quot;\1&quot;,f) #mr_cat to cat</pre><pre>f = f.lower()      #lower case</pre><pre>f = re.sub(r&#39;\b\w{1,2}\b&#39;,&quot; &quot;,f) #remove words &lt;2</pre><pre>f = re.sub(r&quot;\b\w{15,}\b&quot;,&quot; &quot;,f) #remove words &gt;15</pre><pre>f = re.sub(r&quot;[^a-zA-Z_]&quot;,&quot; &quot;,f)  #keep only alphabets and _<br>                                        <br>f = re.sub(r&quot; {2,}&quot;, &quot; &quot;, f, flags=re.MULTILINE) # REMOVE THE EXTRA SPACES</pre><h3>Final Data Preparation</h3><p>As mentioned earlier, the whole preprocessing has been put together in a single function which returns five values. Passing our data to this function-</p><pre>doc_num, label, email, subject, text = preprocessing(prefix)</pre><p>Creating a dataframe which contains the preprocessed email, subject and text. The class labels have been replaced with intergers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NzgeH7ISsRkKNt4fEFL3IA.png" /><figcaption>Preprocessed text is the concatenation of all three</figcaption></figure><h3>Vectorization</h3><p>After splitting the data into train and test (0.25), we vectorize the data into correct form which can be understood by the algorithm. We have used <strong>tokenizer function from keras</strong> which will be used in embedding vector.</p><blockquote><strong><em>Finally encode the text and pad them to create a uniform dataset.</em></strong></blockquote><h3>Model</h3><p>Our model to train this dataset consists of three ‘<strong>one dimensional convolutional’</strong> layer which are concatenated together and passed through other various layers given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*jwQvGjxK7ZXwUS98gX1_yw.png" /><figcaption>The last block is our final output (softmax, categorical_crossentropy)</figcaption></figure><h3>Conclusion</h3><p>After training the model, we get <strong>around 75%</strong> <strong>accuracy </strong>which can be easily furthur improved by making some tweaks in the model. The main focus of this article was the preprocessing part which is the tricky part here.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb206e7274ed" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-i-preprocessed-text-data-using-regular-expressions-for-my-text-classification-task-cnn-cb206e7274ed">How I preprocessed text data using Regular Expressions for my Text classification task (CNN)</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting Damage to Building due to earthquake using Data Science]]></title>
            <link>https://medium.com/swlh/predicting-damage-to-building-due-to-earthquake-using-data-science-e85a62adc0c0?source=rss-b43b4573bdb6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e85a62adc0c0</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[disaster-management]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Rishang Prashnani]]></dc:creator>
            <pubDate>Sun, 03 May 2020 19:32:58 GMT</pubDate>
            <atom:updated>2021-04-19T06:10:47.647Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VWLiuxoW44qoZw0e5gm9OQ.jpeg" /><figcaption>Image courtesy of <a href="https://commons.wikimedia.org/wiki/File:2015_Earthquake_in_Nepal-Pashupatinath_Temple_Area_(12).JPG">Wikimedia Commons</a></figcaption></figure><h3><strong>Table of Contents</strong></h3><ol><li>Introduction</li><li>Understanding the Data</li><li>Exploratory Data Analysis</li><li>Feature engineering</li><li>Relation between <strong>Geo locations</strong> with LSTMs</li><li>Description of Methodology</li><li>Final Preprocessed Data</li><li>Training and Evaluation</li><li>Conclusion</li><li>References</li></ol><h3>Introduction</h3><p>As we are diving deep into the field of artificial intelligence, we are coming across ways in which AI can leverage human life and potentially save them from disasters in the coming future. One such small step towards this <strong>far but promising future</strong> is to use data from past and find some patterns which are universal in nature and which can promise some accurate prediction thereby helping humans minimize the effects of disaster. In this article, I am going to explain my approach to predict the damage to building occurred during the <strong>2015 Nepal earthquake</strong>. This is a competition held by <a href="https://www.drivendata.org/competitions/57/nepal-earthquake/">Driven Data</a>.</p><p>The whole code to this project can be found <a href="https://github.com/Rishang007/Earthquake_damage">here</a>.</p><h3>Understanding the data</h3><p>We’re trying to predict the <a href="https://www.ma.utexas.edu/users/mks/statmistakes/ordinal.html">ordinal variable</a> damage_grade, which represents a level of damage to the building that was hit by the earthquake. There are 3 grades of the damage:</p><ul><li>1 represents low damage</li><li>2 represents a medium amount of damage</li><li>3 represents almost complete destruction</li></ul><p>There are 39 columns in this dataset, where the building_id column is a unique and random identifier.</p><h4><strong>Description</strong></h4><ul><li>geo_level_1_id, geo_level_2_id, geo_level_3_id (type: int): geographic region in which building exists, from largest (level 1) to most specific sub-region (level 3). Possible values: level 1: 0-30, level 2: 0-1427, level 3: 0-12567.</li><li>count_floors_pre_eq (type: int): number of floors in the building before the earthquake.</li><li>age (type: int): age of the building in years.</li><li>area_percentage (type: int): normalized area of the building footprint.</li><li>height_percentage (type: int): normalized height of the building footprint.</li><li>land_surface_condition (type: categorical): surface condition of the land where the building was built. Possible values: n, o, t.</li><li>foundation_type (type: categorical): type of foundation used while building. Possible values: h, i, r, u, w.</li></ul><p>Details of all the 38 features can be found <a href="https://www.drivendata.org/competitions/57/nepal-earthquake/page/136/"><strong>here</strong></a><strong>.</strong></p><h4>Loading the dataset</h4><pre>X = pd.read_csv(&#39;/content/drive/My Drive/data_ml/Richters Predictor Earthquake Damage/train_values_RP.csv&#39;, index_col=&#39;building_id&#39;)</pre><pre>Y= pd.read_csv(&#39;/content/drive/My Drive/data_ml/Richters Predictor Earthquake Damage/train_labels_RP.csv&#39;,index_col=&#39;building_id&#39;)</pre><h3>Exploratory Data Analysis</h3><ol><li><strong>Count plot of the buildings</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DthWuUhWr5OG4nlIrnU-DA.png" /></figure><p>Most of the buildings suffered level-2 damage.</p><h3>Feature Engineering of Geo level ID</h3><p>I have used Random Forest Classifier for this project. Random Forest Classifier is a bagging technique which is an ensemble of <strong>deep decision trees (high variance-low bias or overfitted models). </strong>Random Forest Classifier thus focus on decreasing the variance in any decision making.</p><p>Decision trees are not efficient if any feature has a lot of categories. For example, zip codes of cities has a lot of values which is not ideal for the decision trees.</p><p>Similarly in this dataset, the geo level IDs have a big range of values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xTFQWS6YzYeDT_sC4_IoFg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jSx7JYvSYvJPUQljoDHgrQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tUxjnXk3pClkqCwbayOvQQ.png" /></figure><p>geo_level_3_id has 11595 different types of values, geo_level_2_id has 1414 different types of values. geo_level_1_id has 64 different types of values (although this does not have a large number of values, still we feature engineered it.)</p><p><strong>To overcome this, I applied a feature engineering technique</strong> <strong>replacing the values with their conditional probabilities with respect to every outcome.</strong> <strong>So, every column of geo_lev is replaced by 3 columns for each outcome (y).</strong></p><p>For example, P(y=1 | x=6) for geo_level_1 inplace of where X[geo_level_1_id]=6 and damage_grade = 1 .We do this for all the geo_levels with all the outcomes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oA-eB1EuRla2BNdqkQ92uA.png" /><figcaption>We do the same for geo_level_2 and geo_level_3</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QnFr56WkVa4Sjqwj_Cf3NQ.png" /><figcaption>Probability values replacing the original geo levels</figcaption></figure><h4>Code snippet of feature engineering</h4><pre>fea = pd.merge(X, Y, on=&#39;building_id&#39;)</pre><pre>damage1 = {}<br>damage2 = {}<br>damage3 = {}</pre><pre>for i,j in (X[&#39;geo_level_1_id&#39;].value_counts()).iteritems():</pre><pre>    n1 = len(fea[fea[&#39;damage_grade&#39;]==1][fea[&#39;geo_level_1_id&#39;]==i])<br>    n2 = len(fea[fea[&#39;damage_grade&#39;]==2][fea[&#39;geo_level_1_id&#39;]==i])<br>    n3 = len(fea[fea[&#39;damage_grade&#39;]==3][fea[&#39;geo_level_1_id&#39;]==i])</pre><pre>damage1[i] = n1/j<br>damage2[i] = n2/j<br>damage3[i] = n3/j</pre><pre>list1 = []<br>list2 = []<br>list3 = []</pre><pre>for i in X[&#39;geo_level_1_id&#39;]:<br>    list1.append(damage1.get(i))<br>    list2.append(damage2.get(i))<br>    list3.append(damage3.get(i))</pre><pre>X[&#39;prob1_geo1&#39;] = list1<br>X[&#39;prob2_geo1&#39;] = list2<br>X[&#39;prob3_geo1&#39;] = list3</pre><h3>Relation between <strong>Geo levels</strong> with LSTMs</h3><p>This part’s a little tricky. As I looked into the data, I found some relations between these three levels of locations. Geo level-3 is the most small scale location under geo level 2 which is again under level-1 being the large scale location.</p><p>For a particular value of location-1 and location-2, there are a large number of same values of location-3. An example-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tK_Hx6pYrD1nCHfErh1P7w.png" /><figcaption>12198, 7439, 139 occurs a lot of times for geo_lev_1=6 and geo_lev_2=487.</figcaption></figure><h4><strong>LSTMs</strong></h4><p>Long Short Term Memory is a type of recurrent neural network. LSTMs are different than normal RNNs as they have feedback network. LSTMs are very good for using in sequential data prediction especially in the field of <strong>machine translation</strong>.</p><p>I have applied a similar kind of method to feature engineer these geo levels. There seems to be a sequential relation between the geo levels as level-1 is the highest and so on. <strong>So, I created a special input for LSTM which is a sequence of geo level 1 and geo level 2 and output is geo level-3</strong></p><ul><li>Intuitively we are giving sequence of geo level 1 and level 2 as input to our model which predicts geo level 3.</li><li>After training the data, we take the output of the LSTM layer (intermediate layer) and use it as features for our earthquake prediction</li><li>The idea behind this is to find the relation between these geo levels in mathematical format.</li></ul><h3>Description of Methodology</h3><blockquote>To start with, we need to understand what kind of input <strong>RNN </strong>requires.</blockquote><p>The type of input LSTMs require is</p><pre>( # Datapts, # Timestamps, dimension of vector ) </pre><p>Timpstamps means “<strong>number of words or number of sequence” in a data point. It is the time axis.</strong></p><blockquote><strong>To get the right format, we mimic the work of an embedding layer and keras tokenizer function.</strong></blockquote><ul><li>First, I concatenate geo_level_1_id and geo_level_2_id together and pass it through one_hot_encoder to get the shared vocab or dimension of each sequence. This is just like we do it in NLP, we have words as a sequence and we pass it through Tokenizer to get vocab_size.</li></ul><pre># l1 is series df of lev1 # l2 is series df of lev2<br>inp = pd.concat([l1,l2]).to_numpy().reshape(-1,1)</pre><pre>#get shared vocab of l1 and l2<br>onehot = OneHotEncoder(sparse=False)<br>onehot.fit(inp)</pre><ul><li>Now, I transform l1 and l2 separately to get their one hot vectors. This results in same size of vector for sequence-1 which is geo_level_1 and sequence-2 which is geo_level_2 according to the requirements of an RNN.</li></ul><pre>l1_hot = onehot.transform(l1)<br>l1_hot.shape</pre><pre>&gt;&gt;&gt; (347469, 1419)</pre><pre>l2_hot = onehot.transform(l2)<br>l2_hot.shape</pre><pre>&gt;&gt;&gt; (347469, 1419)           #both have same # datapts and dimension</pre><ul><li>Now the final part, getting the right form of input for an LSTM. It needs a sequence of data with each one_hot sequence side by side. We give it by using numpy stack.</li></ul><pre>fin_inp = np.stack((l1_hot,l2_hot), axis=1)<br>fin_inp.shape</pre><pre>   &gt;&gt;&gt; (347469, 2, 1419)</pre><p>This is exactly what an LSTMs wants as an input. This can be easily described by the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b7cbZv4MB1f3gotRnXX5xA.png" /><figcaption>RNN training to get the context vector</figcaption></figure><p><strong>Note: We cannot use </strong><em>word_embedding</em><strong> because there are no word embeddings here, there is only one_hot_vector of each sequence which are stacked together to create the right form of input for RNN. Basically mimicing the embedding algorithm</strong></p><h4>RNN Model</h4><pre>inpx = Input( shape=fin_inp.shape[1:] )<br>lstm = LSTM(20, )(inpx)<br>lvl3 = Dense(l3_hot.shape[1], activation=&#39;sigmoid&#39;)(lstm)</pre><pre>modelf = Model(inputs= inpx, outputs=lvl3)<br>modelf.compile(loss=&#39;binary_crossentropy&#39;, optimizer=&#39;adam&#39;)<br>modelf.summary()</pre><pre>&gt;&gt;&gt; Output<br>Model: &quot;model&quot; _________________________________________________________________ Layer (type)                 Output Shape              Param #    ================================================================= input_1 (InputLayer)         [(None, 2, 1419)]         0          _________________________________________________________________ lstm (LSTM)                  (None, 20)                115200     _________________________________________________________________ dense (Dense)                (None, 11861)             249081     ================================================================= Total params: 364,281 <br>Trainable params: 364,281 <br>Non-trainable params: 0</pre><p><strong>Fitting the model</strong></p><pre>l3_hot = np.array(pd.get_dummies(l3)) #l3 is geo_lev_3 df</pre><pre>modelf.fit(fin_inp, l3_hot, epochs=10, batch_size=64)</pre><pre>Epoch 1/10<br>5430/5430 [=================] - 33s 6ms/step - loss: 0.0185<br>Epoch 2/10<br>5430/5430 [=================] - 33s 6ms/step - loss: 8.3740e-04<br>Epoch 3/10<br>5430/5430 [=================] - 34s 6ms/step - loss: 8.3151e-04<br>.<br>.<br>.<br>Epoch 9/10<br>5430/5430 [=================] - 33s 6ms/step - loss: 7.0521e-04<br>Epoch 10/10<br>5430/5430 [=================] - 32s 6ms/step - loss: 6.7878e-04</pre><blockquote><strong>Final most important step → getting the context output of the intermediate layer which is the relation between these geo_levels acting as our features.</strong></blockquote><p>layers[1] is the output of LSTM layer which we want</p><pre>inter = Model(inputs=modelf.input, outputs=modelf.layers[1].output)</pre><p>Getting the fin_inp with the same method and predicting to get our required features.</p><pre>fin_inp_train = np.stack((l1_hot,l2_hot), axis=1)<br>fin_inp_train.shape</pre><pre>&gt;&gt;&gt; (260601, 2, 1419)</pre><pre>fin_inp_test = np.stack((l1_hot,l2_hot), axis=1)<br>fin_inp_test.shape</pre><pre>&gt;&gt;&gt; (86868, 2, 1419)</pre><pre><br>geo_fea_train = inter.predict(fin_inp_train)</pre><pre>geo_fea_test = inter.predict(fin_inp_train)</pre><h3>Final Preprocessed Data</h3><p>For our final data, we drop the geo_levels and create a one_hot of all the remaining features. Stack them with our newly created geo_fea_train features.</p><p>Note: Probabilities calculated have already been added to the data.</p><pre>fx_tr = np.hstack((np.array(pd.get_dummies(X.copy().drop([&#39;geo_level_1_id&#39;, &#39;geo_level_2_id&#39;, &#39;geo_level_3_id&#39;], axis=1))), geo_fea_train))</pre><pre>fx_tr.shape</pre><pre>  &gt;&gt;&gt; (260601, 94)</pre><pre>fx_te = np.hstack((np.array(pd.get_dummies(test.copy().drop([&#39;geo_level_1_id&#39;, &#39;geo_level_2_id&#39;, &#39;geo_level_3_id&#39;], axis=1))), geo_fea_test))</pre><pre>fx_te.shape</pre><pre> &gt;&gt;&gt; (86868, 94)</pre><pre>fy_tr = Y.to_numpy().ravel()<br>fy_tr.shape</pre><pre> &gt;&gt;&gt; (260601,)</pre><h3>Training and Evaluation</h3><p>We are using grid search CV and Random Forest here.</p><pre>param = {&#39;n_estimators&#39;: [ 500, 1000], <br>&#39;min_samples_split&#39;:[20, 50, 500]}</pre><pre>clf = RandomForestClassifier()</pre><pre>gd_sr = GridSearchCV(estimator=clf,param_grid=param,scoring=&#39;f1_micro&#39;,cv=5,n_jobs=-1)</pre><pre>gd_sr.fit(fx_tr, fy_tr)</pre><p>Output</p><pre>gd_sr.best_score_</pre><pre>&gt;&gt;&gt; 0.75467870076</pre><pre>gd_sr.best_params_</pre><pre>&gt;&gt;&gt; {&#39;min_samples_split&#39;: 20, &#39;n_estimators&#39;: 1000}</pre><h3>Conclusion</h3><p>Using the best parameters, I trained the model and predicted the test values. Got a position of top 3% in the competition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yu1NKg2UExctC4Gv1wAUlw.jpeg" /><figcaption>Check the result <a href="https://www.drivendata.org/users/Rishang/">here</a></figcaption></figure><h3>References</h3><p><a href="https://www.drivendata.org/competitions/57/nepal-earthquake/">Richter&#39;s Predictor: Modeling Earthquake Damage</a></p><p><a href="https://colah.github.io/posts/2015-08-Understanding-LSTMs/">https://colah.github.io/posts/2015-08-Understanding-LSTMs/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e85a62adc0c0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/predicting-damage-to-building-due-to-earthquake-using-data-science-e85a62adc0c0">Predicting Damage to Building due to earthquake using Data Science</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>