<?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 Kunal Mishra on Medium]]></title>
        <description><![CDATA[Stories by Kunal Mishra on Medium]]></description>
        <link>https://medium.com/@kunalmishra78?source=rss-243c692f45d6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*h2KwrqxaFuj-jEm4.jpg</url>
            <title>Stories by Kunal Mishra on Medium</title>
            <link>https://medium.com/@kunalmishra78?source=rss-243c692f45d6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 07:09:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kunalmishra78/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[Part 1. Input Embeddings and Positional Encodings]]></title>
            <link>https://medium.com/@kunalmishra78/part-1-input-embeddings-and-positional-encodings-343fca6ecc2e?source=rss-243c692f45d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/343fca6ecc2e</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Kunal Mishra]]></dc:creator>
            <pubDate>Sat, 06 Jan 2024 23:16:24 GMT</pubDate>
            <atom:updated>2024-01-07T16:43:58.437Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>Github Repo — </em></strong><a href="https://github.com/mishra-kunal1/Attention-is-all-you-need/tree/main"><strong><em>Repo Link</em></strong></a></p><p><strong><em>Colab notebook — </em></strong><a href="https://github.com/mishra-kunal1/Attention-is-all-you-need/blob/main/Attention_is_all_you_need.ipynb"><strong><em>Notebook</em></strong></a></p><p><strong><em>Preprocessed Dataset — </em></strong><a href="https://drive.google.com/file/d/1sD3WFeY_0ulkiskkJFuuvDkDdxFWsAu1/view"><strong><em>Dataset</em></strong></a></p><p>This is the second blog of the series implementing the “<strong>Attention is all you need”</strong> research paper from scratch. Here are the links for the other parts</p><p>Part 0. <a href="https://medium.com/@kunalmishra78/attention-is-all-you-need-paper-implementation-from-scratch-on-colab-7679289d1022"><strong><em>Intro blog</em></strong></a></p><p>Part 2. Multihead attention (in progress)</p><p>Part 3. Encoder block (in progress)</p><p>Part 4. Decoder block (in progress)</p><p>Part 5. Assembling the model and training (in progress)</p><p>Part 6. Inference (in progress)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T8WWibd7u8b7gfgeG0LgAA.gif" /></figure><h3><strong>Input Embeddings</strong></h3><h4>First, we will try to understand what are input embedding and why they are needed.</h4><p>We deal with text data in Natural Language Processing (NLP) based problems. To give the text as input to any machine learning model we need to convert them to numbers.</p><p>Now one of the ways to convert the given input sentence to numbers is to first break down the sentence into individual words and then assign a number to each word. The process of breaking down text into smaller units (tokens) is called <strong>tokenization</strong>.</p><p>For example:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*48QC_IX2TL_YFcDFb5m-mg.gif" /><figcaption>Text tokenization and vectorization</figcaption></figure><p>This is called word-level tokenization. One of the best tokenization techniques is to use byte-level encoding tokenization such as <a href="https://github.com/openai/tiktoken">tiktoken</a> tokenizer which is used by OpenAI or <a href="https://github.com/google/sentencepiece">sentencepiece</a> which is used by Google.</p><p>Next, we need to represent these word-level tokens into vectors so that they convey some meaning. We will create these vectors using the <a href="https://pytorch.org/docs/stable/generated/torch.nn.Embedding.html">nn.Embedding</a> layer. This layer can be thought of as a dictionary(lookup table) of size<em> vocab_size X embedding_size</em>. Each row will contain float values and will be of size embedding_size. The embedding size is a hyperparameter and is referred to as <em>d_model</em> in the original paper and the value taken was 512 i.e. each word was represented as 512 dim vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Iz5rVr05IyiZuQxsC2y0Pw.gif" /><figcaption>Embedding layer</figcaption></figure><p>The Embedding layer is trainable and as we train the model the values in the Embedding layer change to minimize the loss. We’ll look in the last section at the final values of the embedding layer.</p><p><strong>Size is important </strong>— Let’s calculate the size after this operation. For the given sentence “I am going to school” the number of words is 5. Let’s assume the embedding dimension(d_model) to be 512. After encoding we’ll get a vector of shape 5x 512. (as evident in the above image)</p><p><strong>Size for a batch of inputs</strong> — To speed up the training process instead of giving a single input sentence it is a common practice to give a batch of input sentences to the model. The sentences in a particular batch are independent of each other and are processed in parallel.</p><p><strong>Problem</strong> — The size of individual sentences in a given batch can be different. The encoded vector of the sentence “I am going to school” will be of size 5 x 512 whereas the encoded vector of the sentence “Tim plays soccer” will be of size 3 x 512.</p><p><strong>Solution</strong> — To tackle this problem we define two things, maximum sentence length, and pad token.</p><ol><li>If the character length of the sentence is greater than the maximum length we will clamp there.</li><li>If the character length of the sentence is less than the maximum length then we will pad the sentence with a pad token.</li></ol><p>Let’s say we define the batch size as 8, and the maximum word length as 32 so the batch input given to the model will be 8 x 32 x 512; we’ll call this (B x M X d_model)</p><h3>Position encodings</h3><h4>Now, we will try to understand what are position encodings and why they are needed.</h4><p>In any language, the order of the words matters. If we change the positions of the words in any given sentence, the entire meaning can be altered.</p><p><strong>Problem</strong> — The transformer models don’t use any of the recurrence or convolution operations and hence there is no notion of positions in which the words are occurring</p><p><strong>Solution — </strong>To solve the above problem position encodings of words of a sentence are also given along with the sentences to give positional information.</p><p>The position encodings used in the original paper involve sine and cosine functions operated on the position of the token. The positional embedding matrix will be of size <strong><em>max_length</em> x <em>embedding_dim </em></strong>where each row represents the encoded positional information. Here’s how the values are calculated in the paper</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*xdkChg6_393ijCNBRRbQRA.png" /></figure><p>Note — The values in the positional embedding matrix will be pre-computed they won’t change during training. Here’s the snippet to compute positional encodings</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c292fd22f0d2313e3e44f8a982051cc2/href">https://medium.com/media/c292fd22f0d2313e3e44f8a982051cc2/href</a></iframe><p>For a given sentence the position encodings are obtained as follows</p><ol><li>Get the max_length of the inputs.</li><li>Create a <strong>range_vector </strong>using torch.arange(max_length) which will give output as [0,1,2,3,…..max_length-1]</li><li>Get the embeddings of each element in the range vector from the position embeddings matrix defined above.</li></ol><p>The output you’ll get will be B x M x d_model</p><h3>Final Inputs</h3><p>Now, we have both input and positional embeddings for a batch of input. To club them together we sum them directly as both are of size B x M x d_model. The input that goes inside the Encoder is a matrix of size B x Mx d_model. The complete process works as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vBVUjFKqdklUrak-bU8Lng.gif" /><figcaption>Preparing data to be fed into encoder</figcaption></figure><p>Till now we have seen how the inputs are fed to the encoder as shown in the snippet</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*bRBs-QmRpZ_o1DEZH0gv2A.png" /><figcaption>Snippet from the Research paper</figcaption></figure><p>Now in the next part, we will check the Multihead attention and Encoder part.</p><p><strong><em>Github Repo — </em></strong><a href="https://github.com/mishra-kunal1/Attention-is-all-you-need/tree/main"><strong><em>Repo Link</em></strong></a></p><p><strong><em>Colab notebook — </em></strong><a href="https://github.com/mishra-kunal1/Attention-is-all-you-need/blob/main/Attention_is_all_you_need.ipynb"><strong><em>Notebook</em></strong></a></p><p><strong><em>Preprocessed Dataset — </em></strong><a href="https://drive.google.com/file/d/1sD3WFeY_0ulkiskkJFuuvDkDdxFWsAu1/view"><strong><em>Dataset</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=343fca6ecc2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Attention Is All You Need — Paper implementation from scratch on Colab]]></title>
            <link>https://medium.com/@kunalmishra78/attention-is-all-you-need-paper-implementation-from-scratch-on-colab-7679289d1022?source=rss-243c692f45d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/7679289d1022</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Kunal Mishra]]></dc:creator>
            <pubDate>Sat, 06 Jan 2024 23:06:09 GMT</pubDate>
            <atom:updated>2024-01-07T16:43:18.983Z</atom:updated>
            <content:encoded><![CDATA[<h3>Attention Is All You Need — Paper implementation from scratch on Colab</h3><p><strong><em>Github Repo — </em></strong><a href="https://github.com/mishra-kunal1/Attention-is-all-you-need/tree/main"><strong><em>Repo Link</em></strong></a></p><p><strong><em>Colab notebook — </em></strong><a href="https://github.com/mishra-kunal1/Attention-is-all-you-need/blob/main/Attention_is_all_you_need.ipynb"><strong><em>Notebook</em></strong></a></p><p><strong><em>Preprocessed Dataset — </em></strong><a href="https://drive.google.com/file/d/1sD3WFeY_0ulkiskkJFuuvDkDdxFWsAu1/view"><strong><em>Dataset</em></strong></a></p><p>If you ask any person, what’s the hottest topic in tech right now you’ll get the same answer most of the time <strong>LLMs</strong>. ChatGPT, LLama, and BloombergGPT have taken down the internet and shown the world what AI is capable of.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/0*oyxXB0bZ7pagGxJV" /></figure><p>I also wanted to dive into this fascinating world of LLM’s but I didn’t know where to start from. After a bit of research, I decided to go through the research paper which has the core algorithm (the Transformers architecture) that all LLMs follow and that has been cited more than 100k times <strong>“Attention is all you Need”</strong> and tried to implement the transformer based encoder-decoder model on Colab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*8Pw6Nk7okWwrkBmOWLwtdg.gif" /><figcaption>Transformers — The secret sauce for all the LLMs recipes</figcaption></figure><p><strong>What Machine Learning problem are we trying to solve?</strong></p><p>At a higher level, the problem that is being discussed in the paper is to <strong>predict the next word, given some inputs.</strong> (that’s what all LLMs do as well) Specifically in this paper sequence transduction (translation of one language to another) task is implemented using a transformer-based encoder-decoder architecture. The architecture of the model is as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fQlQGjFKeQkYaFZlzbxsXg.png" /><figcaption>Model architecture as described in the paper</figcaption></figure><p>At first, the architecture is quite overwhelming as it has multiple components. For a better understanding of the complete workflow, I have decided to split the blog into multiple posts.</p><ol><li><a href="https://medium.com/@kunalmishra78/part-1-input-embeddings-and-positional-encodings-343fca6ecc2e"><strong>Input Embeddings and Positional Encodings</strong></a></li><li><strong>Multi Head Attention</strong></li><li><strong>Encoder</strong></li><li><strong>Decoder</strong></li><li><strong>Training the model</strong></li><li><strong>Inference</strong></li></ol><p>Three things that are very important in Deep Learning are</p><ol><li>Why we are doing this operation?</li><li>How are we doing this operation?</li><li>What will be the output shape after this operation?</li></ol><p>In the upcoming blogs, I’ll try to answer the hows and the output shape through code and animation. It’s not possible to answer all why in the short blogs so I’ll put down a few links for the same.</p><p><strong><em>Here’s the link to the Colab notebook — </em></strong><a href="https://github.com/mishra-kunal1/Attention-is-all-you-need/blob/main/Attention_is_all_you_need.ipynb"><strong><em>Notebook</em></strong></a></p><h4><strong>Data Loading and Preprocessing</strong></h4><p>There are multiple ways to load the data and preprocess it. The dataset that I followed in this implementation can be downloaded from this <a href="https://www.manythings.org/anki">link</a>. I have used the English German pair of sentences to train the model. One can find the preprocessed data <a href="https://drive.google.com/file/d/1sD3WFeY_0ulkiskkJFuuvDkDdxFWsAu1/view">here</a>. However, the code can be used for translation tasks for any pair of datasets. The original model was trained on the WMT2014 English-German dataset.</p><p>After loading the dataset the first thing is to tokenize and vectorize the text. This we will do in the second blog.</p><p>Next Blog — <a href="https://medium.com/@kunalmishra78/part-1-input-embeddings-and-positional-encodings-343fca6ecc2e"><strong>Input Embeddings and Positional Encodings</strong></a></p><p><strong><em>Github Repo — </em></strong><a href="https://github.com/mishra-kunal1/Attention-is-all-you-need/tree/main"><strong><em>Repo Link</em></strong></a></p><p><strong><em>Colab notebook — </em></strong><a href="https://github.com/mishra-kunal1/Attention-is-all-you-need/blob/main/Attention_is_all_you_need.ipynb"><strong><em>Notebook</em></strong></a></p><p><strong><em>Preprocessed Dataset — </em></strong><a href="https://drive.google.com/file/d/1sD3WFeY_0ulkiskkJFuuvDkDdxFWsAu1/view"><strong><em>Dataset</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7679289d1022" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Signs Speak Louder Than Words]]></title>
            <link>https://medium.com/@kunalmishra78/signs-speak-louder-than-words-de0197780c95?source=rss-243c692f45d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/de0197780c95</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[asl]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Kunal Mishra]]></dc:creator>
            <pubDate>Thu, 23 Feb 2023 00:19:21 GMT</pubDate>
            <atom:updated>2023-02-23T00:49:25.268Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Developing an Image Recognition Model for American Sign Language (ASL)</strong></h4><p>The ability to communicate effectively is an essential aspect of human existence, yet it remains a challenge for individuals who experience hearing or verbal impairments. Fortunately, American Sign Language (ASL) serves as a bridge that connects these individuals to the broader society, allowing them to express themselves and establish meaningful connections.</p><p>The aim of the project is to train a model to recognize sign language in real time, using a webcam as the input source.</p><p><strong>Note — </strong>Please find the link to the PyTorch implementation of the project <a href="https://github.com/mishra-kunal1/ASL_classification">here</a> and the Tensorflow implementation of the project <a href="https://github.com/mishra-kunal1/ASL_classification/tree/main/tensorflow_version">here</a>. The code can be extended to perform image classification on any dataset by just modifying the path and number of classes.</p><h4>Modeling the given problem as a Deep Learning Project</h4><p>Any deep-learning project can be compared to a 6 jars analogy, each representing a different aspect of the project. These jars comprise:</p><ol><li><strong>Data</strong> — What kind of data is being used?</li><li><strong>Task</strong> — What is the objective of the project?</li><li><strong>Models</strong> — What models will be utilized in training?</li><li><strong>Loss</strong> <strong>function and performance metric</strong> — What is the criterion for evaluating the performance of the model?</li><li><strong>Training and learning </strong>— How will the models be trained and learned from the data?</li><li><strong>Testing</strong> — How well does the model perform on the test data?</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*xVX9YejttpQwaBE91Nmwmg.jpeg" /></figure><p>Let’s explore these jars one by one</p><h4>1. What is the data?</h4><p>The dataset we are going to use is Kaggle’s <a href="https://www.kaggle.com/datasets/grassknoted/asl-alphabet">ASL Alphabet dataset</a>. The dataset is a collection of images of alphabets from American Sign Language, separated into 29 folders that represent the various classes.</p><p>The training data set contains 87,000 images which are 200x200 pixels. There are 29 classes, of which 26 are for the letters A-Z and 3 classes for <em>SPACE</em>, <em>DELETE,</em> and <em>NOTHING</em>. These 3 classes are very helpful in real-time applications and classification. In testing data, there are only 29 images, but in this project, we will give input images directly through the webcam and predict the classes.</p><p><strong>Visualizing some of the training samples</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OpUzjiRhOrib3UbPXtiW0Q.png" /></figure><p><strong>Visualizing the number of images for each class</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VmhFOsmUmxU00YmeHwALOA.png" /></figure><p>It is clear from the above diagram that we are dealing with a balanced multi-class classification problem.</p><h4>Preprocessing the data</h4><p>In order to give the images as input to a deep learning model we need to perform some preprocessing. We are converting the input images to tensors after resizing them. We are splitting the dataset into train and validation sets in an 80:20 ratio in order to prevent overfitting. Finally, we are creating batches of 32 images in order to give input to the model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61c9518a05abd33bb56dfc4a6dffbfbc/href">https://medium.com/media/61c9518a05abd33bb56dfc4a6dffbfbc/href</a></iframe><h4>2. What is the task?</h4><p>The task is to build an Image classification model that can accurately classify images of American Sign Language in one of the 29 classes.</p><p>It’s important for the model to respond quickly as it’s expected to make real-time predictions. In addition, it’s essential for the model to minimize inaccurate predictions by reducing false positives and false negatives.</p><h4>3. What are the models that we are going to train?</h4><p>Since this is an image classification problem we have two options.</p><ol><li>Define our custom model and train the model from scratch</li><li>Use transfer learning and load a pre-trained model, modify the last layer of the model according to the given dataset, and train only the parameters of the last layers.</li></ol><p>Here’s the code we have written for the pre-trained model</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/230115ca4afe821b0fb06323c71be63c/href">https://medium.com/media/230115ca4afe821b0fb06323c71be63c/href</a></iframe><h4>4. <strong>Loss function and performance metric</strong></h4><p>Since we are dealing with multiple classes we are going to use Cross entropy loss (also called Multiclass log loss).</p><p>Also, the given problem has a roughly equal number of samples for each class and hence we can use accuracy as a metric.</p><h4><strong>5. Model training and learning</strong></h4><p>This part is the heart of the whole project. After we have defined the dataset, the model, and the loss function we finally need to train the model.</p><p>We have trained the model on free GPU (Kaggle’s P100 and Google Colab’s Tesla K80) for 10 epochs using Adam optimizer with a batch size of 32 and these are the results we got</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TyRb9yxDW_0tWcma4d_B3Q.png" /></figure><p>It is clear from the above table that pre-trained models are performing better than the custom models. However, the TensorFlow pre-trained model is overfitting, we can try to use dropouts and data augmentation to reduce the overfitting.</p><h4>6. Inference</h4><p>While training the model we are storing the trained weights of the model. During the inference time, we load these weights directly into the model.</p><p>We are also using the cv2 library to read the image from the webcam and performing the same transformations of the test image that we used on the train images before giving input to the model. Finally, we are displaying the predicted class as output.</p><p>Here are the results</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*utCP1a-_ckF178szCLF7gw.gif" /></figure><p><strong>Future works</strong></p><ol><li>Add RNN, LSTMs, and Attention networks to this model in order to make it end to end ASL detection application that can predict words.</li></ol><p>2. Add better techniques to infer the image in real-time.</p><p><strong>References</strong></p><ol><li>Github repo — <a href="https://github.com/mishra-kunal1/ASL_classification">https://github.com/mishra-kunal1/ASL_classification</a></li><li><a href="https://www.kaggle.com/datasets/grassknoted/asl-alphabet">https://www.kaggle.com/datasets/grassknoted/asl-alphabet</a></li><li><a href="https://www.guvi.in/">https://www.guvi.in/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de0197780c95" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Very comprehensive blog Ankit.]]></title>
            <link>https://medium.com/@kunalmishra78/very-comprehensive-blog-ankit-a6dfa6df0f26?source=rss-243c692f45d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6dfa6df0f26</guid>
            <dc:creator><![CDATA[Kunal Mishra]]></dc:creator>
            <pubDate>Thu, 15 Dec 2022 18:00:03 GMT</pubDate>
            <atom:updated>2022-12-15T18:00:03.359Z</atom:updated>
            <content:encoded><![CDATA[<p>Very comprehensive blog Ankit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6dfa6df0f26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Context-based Question Answering System on SQuAD 2.0]]></title>
            <link>https://medium.com/@kunalmishra78/building-a-context-based-question-answering-system-on-squad-2-0-cc33aeb61d13?source=rss-243c692f45d6------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc33aeb61d13</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[squad]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Kunal Mishra]]></dc:creator>
            <pubDate>Fri, 06 May 2022 21:28:55 GMT</pubDate>
            <atom:updated>2022-05-06T21:28:55.299Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_HAaV2AVkNTSWAlq" /><figcaption>Photo by <a href="https://unsplash.com/@emilymorter?utm_source=medium&amp;utm_medium=referral">Emily Morter</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>1. About the Dataset?</strong></h3><p>Stanford Question Answering Dataset (SQuAD) is a reading comprehension dataset consisting of more than 100k questions. The answer to each question is a segment of text from the corresponding passage. The passages are taken from Wikipedia articles. The file is present in JSON format. Dataset can be downloaded from the following <a href="https://rajpurkar.github.io/SQuAD-explorer/">link.</a></p><p>The structure of the dataset is as follows</p><blockquote>i) <strong>Title </strong>— These are the topics on which the Passages are based upon. There are a total of 442 titles in the data. Each title has multiple comprehensions present under them.</blockquote><blockquote>ii)<strong>Context</strong> — These are the passages that are present in each of the titles. The number of passages for each title varies from 10-to 149. The questions are based on these contexts only.</blockquote><blockquote>iii)<strong>Question and Answers</strong>- For each context, there are a few questions associated with it and the corresponding answers are present.</blockquote><blockquote>iv) <strong>Answers starting index and is_possible </strong>— Each of the rows contains the starting index of the answer from the context and a boolean variable depicting whether it’s possible to answer or not.</blockquote><p><strong>Flowchart to show the structure of SQuAD dataset</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JxwHSSRQSljzBqSL6pGA-Q.png" /></figure><p>The dataset after a little preprocessing looks as follows. The code for preprocessing can be found in the <a href="https://colab.research.google.com/drive/1knbfg6doIwgKRzypwwu12AJdP0uF6O8J">notebook</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YqTRQMMJrJ3sOMJaWwDe3A.png" /></figure><h3>2. EDA and getting the statistical figures</h3><p>First, we will check the total number of datapoints and the number of unique titles and contexts present in our dataframe.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae6aff90e97cd13d9f142b1ca50b5911/href">https://medium.com/media/ae6aff90e97cd13d9f142b1ca50b5911/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fx0wPp6uJ3VmNO0JwqUm2Q.png" /></figure><p>Since we are dealing with text data, we will check the number of words present in the context,questions and answers column in the data frame. We will plot the distribution curve of these columns to get an idea.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/962d0db86e0b7859ad368c03930471c9/href">https://medium.com/media/962d0db86e0b7859ad368c03930471c9/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fUJlGCrIzbCqx8IyHhoiTw.png" /></figure><p>As it is very clear from the above plots that our plots are right skewed and there are outliers present in the dataset. We can remove the datapoints where the number of words in context are greater than 200. Similarly we can remove the datapoints where number of words in question and answer are greater than 50 and 20 respectively.</p><h3>3. Preprocessing and vectorizing the data</h3><p>This is the most important step for our project. As a part of preprocessing we will first remove the outliers discussed in the previous section. We will also convert all the words to lowercase characters.</p><p>We will start vectorization (converting text to numbers) on our preprocessed data. We are using keras.tokenizer to convert our text to tokens. We will not use the methods directly available in keras.preprocessing . We will define a class Vectorization and inside the class the following methods will be defined</p><ol><li><strong>Create_vocabulary</strong>- as the name suggests this method will take all the train text data as input and will create a vocabulary out of it. We are also defining the max_words to set the upper limit on number of tokenizers in the vocabulary.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32e7f8c7cb87989b1076b330f2b8aee6/href">https://medium.com/media/32e7f8c7cb87989b1076b330f2b8aee6/href</a></iframe><p>2.<strong> Text to Seq and Seq to Text- </strong>This is pretty straightforward function in which we convert the text to sequences using the vocabulary that we have created. We will also perform the reverse operation and convert the seq back to text (during the inference process).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b38f6b39e2d0d1d503c9fcccf07c78d5/href">https://medium.com/media/b38f6b39e2d0d1d503c9fcccf07c78d5/href</a></iframe><h3>4. Defining the model</h3><p>A wide variety of models have been already trained on SQuAD dataset. A few models have performed better than humans in term of answering questions given it’s context .You can find more details in this <a href="https://rajpurkar.github.io/SQuAD-explorer/">link. </a>In this project we will define a model from scracth using Bidirectinal GRU units and Attention layers. The architecture of the model will be as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TuP4o9xwPHjwGmAG0W8I7Q.png" /></figure><p>We have taken context and questions as input and there are three output variables. First is the start index of the answer, second is end index of the answer and third is a dense layer with 2 units and activation as softmax to check whether the answer is possible or not. We will fit our model after defining the model checkpoint callback.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u0FaFCLSoUHvpdetg-Wv3w.png" /></figure><h3>5. Inference and interpreting the results</h3><p><strong>Performance metrics for the project</strong></p><p><strong>Exact Match </strong>— The percentage of answers that are exactly correct as our ground truth word to word. The ground truth and the predicted answer should have the same starting and ending index. The higher the percentage value the better will be our model’s performance in understanding the context and the questions and giving exact answers.</p><p><strong>F1 Score </strong>— We use macro averaged F1 score. It captures the precision and recall that words chosen as being part of the answer are actually part of the answer. It measures the average overlap between the prediction and ground truth answer. We treat the prediction and ground truth as bags of tokens, and compute their F1. We take the maximum F1 over all of the ground truth answers for a given question and then average over all of the questions.</p><p>After training the model we have saved the weights and architecture as a .hdf5 file so that we can load the model and check our predictions. We will directly load the model and preprocess the test data to predict the answers for the given questions and context.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7b0e0d08cd22fc185f4340e29b3e5e6/href">https://medium.com/media/c7b0e0d08cd22fc185f4340e29b3e5e6/href</a></iframe><p>After running the evaluation script that was present in the website to check the performance of the model we got the following results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*Fc1mEXPZA21G0i70w0rmgQ.png" /></figure><p>Predicted output for a few datapoints</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*KGshtIAMjniBaAUdvISQ_A.png" /></figure><h3>7. Conclusion and future goals</h3><p>We can get a decent performance if we are training the model from scratch. The model is able to predict one word or two word answers but is not generalized for all lengths of question answers. We can train the model for more number of epochs , we can use more number of GRU units or we can increase the max sequence length for context text and question text for better performance of the model.</p><p>We can also use the pre-trained models such as BiDAF, <a href="https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad">bert-large-uncased</a>, or DrQA models and then fine tune them to get better performance on our data.</p><h3>8. References</h3><ol><li>The Colab notebook for the base model code -<a href="https://colab.research.google.com/drive/1knbfg6doIwgKRzypwwu12AJdP0uF6O8J?usp=sharing">https://colab.research.google.com/drive/1knbfg6doIwgKRzypwwu12AJdP0uF6O8J?usp=sharing</a></li><li>SQuAD dataset link — <a href="https://rajpurkar.github.io/SQuAD-explorer/">https://rajpurkar.github.io/SQuAD-explorer/</a></li><li>HuggingFace model made specifically for Squad — <a href="https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad">https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc33aeb61d13" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>