<?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 Sezaz Qureshi on Medium]]></title>
        <description><![CDATA[Stories by Sezaz Qureshi on Medium]]></description>
        <link>https://medium.com/@sezazqureshi?source=rss-1c8634690d49------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*nhhMnFkoXGxiwaDP</url>
            <title>Stories by Sezaz Qureshi on Medium</title>
            <link>https://medium.com/@sezazqureshi?source=rss-1c8634690d49------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 20:17:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sezazqureshi/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[Object Detection State of the Art-YOLO-V3]]></title>
            <link>https://medium.com/analytics-vidhya/object-detection-state-of-the-art-yolo-v3-79ad2937832?source=rss-1c8634690d49------2</link>
            <guid isPermaLink="false">https://medium.com/p/79ad2937832</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[yolov3]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Sezaz Qureshi]]></dc:creator>
            <pubDate>Sun, 18 Jul 2021 07:21:28 GMT</pubDate>
            <atom:updated>2021-09-15T10:19:51.353Z</atom:updated>
            <content:encoded><![CDATA[<h3>Problem Formulation:</h3><p>sometimes we want to find out what are the contents inside an image so that we can use this information for various reasons for example: if we know what objects are inside an image, what is its extent, and its accurate location we can use it for multiple tasks like classification of different type of objects in a single image, this comes very handily when you are to design a self-driving car. In recent years we have achieved better accuracy for such complex tasks in recent years using the deep learning model. In this blog, we are going to have a look at one such model called YOLO(You Only Look Once) and its 3rd version.</p><p>the task that object detection tries to solve is detecting multiple objects in a single image and localize those objects by drawing a rectangle over them called bounding boxes. a single image could have multiple objects and they have multiple bounding boxes too. have a look at the image for better understanding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*yKlWDBQT7e5OkOsWTOHvNg.jpeg" /><figcaption>object detection. source- google image search.</figcaption></figure><p>So the task that our model solves is given an input image it should return us the bounding boxes for each object which is objection and localization and the second task is of classification which tells its corresponding class label, the class labels will differ from problem to problem.</p><h3>YOLO-V3 model details:</h3><p>Now let&#39;s have a look into the yolov3 model insides. this model constitutes of many parts, but first, let&#39;s talk about the backbone network that is used which is also called a feature extractor, its used to extract important features for object localization and its classification. It&#39;s a fully connected convolution network(FCN) which means it does not have dense layers or max-pooling layers. In earlier versions of this model, they have used VGG and ResNet as the backbone but in the Yolo V3, they used an FCN called DarkNet-53. Which is a 53 layered fully convolution network below is the image of the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*ISLwwI8mCRT5jDvwUhRqrw.jpeg" /><figcaption>Yolo architecture</figcaption></figure><p>The typical input size of the image inside the model is (416x416x3) which is fed into the model.</p><h4>Convolution Block:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*7uk2hd0mkF2FLoIj8NmENw.jpeg" /><figcaption>convolution block</figcaption></figure><p>the convolution block here means it has convolution operation of the filter size mentions beside each block and the size of each kernel is also defined, if in the kernel size you see ‘3 x 3 / 2’ it means the stride is equal to 2 because we don&#39;t use max-pooling operation here we have to use stride operation to reduce the image size you will also notice that the size in output column the size of the image has also reduced the factor of 2</p><p>After the convolution operation, it is passed to the BatchNormalisation layer followed by LeakyRelu activation.</p><h4>Residual Block:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*YfHrr0txuVRIICaLkKrO7g.jpeg" /><figcaption>block</figcaption></figure><p>the residual block idea is derived from ResNet, in which they use residual layers which allow the gradients to skip through the convolution operation if they don’t provide much information. by doing it the flow of gradient becomes smooth and all the non-essential information is ignored by the network.</p><p>in the darknet, the residual block works as follows the as you can see that there are blocks inside a bigger block lets name it mega-block so inside this mega block there are 2 convolutional blocks of different kernel sizes (1,3) and the number of filters is (32,64) respectively after this there is a residual block.</p><p>So the input that comes inside our mega-block is of shape 128*128*64 from the above figure and its passed to the 2 convolution blocks after that the image size is changed into 128*128*64 so what residual block does is it just concatenates the input that was received into our mega-block (128*128*64) with the output of second convolution block which will output the tensor of the same shape as received (128*128*64). so it&#39;s adding a shortcut connection.</p><p>you might have noticed ‘1x,2x,4x,8x’ denoted outside our mega-block. this means that that whole mega block is repeated that number of times. because the input tensor and output tensor shapes are the same we can repeat the operation without any error.</p><p>so once the image is passed into the model the image size is shrunk by 32, because as you see after each block we are applying a convolution block with a stride of 2 five-time so that gives us 2⁵=32. if the image shape passed is 416*416*3 then the extracted features shape will be 13*13*1024 (1024 is the number of filters inside the last mega block).</p><p>so now we have successfully extracted the features from the backbone network, let&#39;s move ahead.</p><h4>3-scale output:</h4><p>It combines low-resolution, semantically strong features with high-resolution, semantically weak features via a top-down pathway and lateral connections.</p><p>As you can see in the architecture, three outputs are going to the prediction from 3 different mega blocks called scale1 whose tensor shape is (52*52*256),scale2 whose shape is (26*26*512),scale3 whose shape is (13*13*1024). This idea is taken from Feature Pyramid Networks (FPN) which is another model for object detection itself.</p><h3>Model output formulation:</h3><p>till now we have seen that how the image is passed through the network, so now let&#39;s see what should be the output of the model.</p><p>till we have down-sampled our image of shape (416*416) into 52*52,26*26,13*13.but so understanding let&#39;s just consider the output feature block of 13*13*1024 output. let&#39;s have a look at the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*db-ryP-IycCChdiCZzrb_Q.png" /><figcaption>Yolo output</figcaption></figure><p>for the prediction purposes first, we will divide our image into 13 x 13 blocks do in our case if the input image is of shape then the total blocks will be (416/13)*(416/13)=32*32, so each block of the grid (marked in red color) let&#39;s say will have a shape of 13 and there will be 32*32 such blocks.</p><p>so each block will contain 3 anchor boxes per grid cell as per the paper and for each cell, there will be 85 values. let me break this down.</p><p>let&#39;s say you are training on the MS-COCO dataset for object detection, we know that it has 80 sets of classes. so this number 85 will divide into 4 bounding box offsets +1 abjectness score + 80 class probabilities=85.</p><h4>Anchor Boxes:</h4><p><em>Anchor boxes</em> are a set of predefined bounding boxes of a certain height and width. this idea is taken from YOLO-V2. they ran k-means clustering on the dimensions of bounding boxes on the MS-COCO dataset to get good priors for the model. The below image shows the average IOU we get with various choices for k. they found that k = 5 gives a good value for recall vs. complexity of the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*lYS3X83Qq_weYyFUQq-uWg.jpeg" /><figcaption>anchor boxes.</figcaption></figure><h4>bounding box offsets:</h4><p><strong>tx and ty: </strong>x and y coordinates of the <strong>offset </strong>of the bounding box for this cell.</p><p><strong>tw and th:</strong> height and width of the bounding box for this cell.</p><p>these are the prediction for each cell. remember these are not the actual bounding boxes coordinates they are just offsets and width and height, we will calculate the actual bounding box using these coordinates.</p><h4>Objectness Score:</h4><p>it is not possible for each and 13*13 anchor-box has an object inside it, so to capture this information we have a binary label which will be 1 if the object is present in the grid cell and 0 otherwise.</p><h4>Class Probabilities:</h4><p>now that we have detected the object now we also want what is the type of this object like in MS-COCO: cat, dog, bird, etc. so if in our dataset we have 80 different then there will be 80 class probability values for each class.</p><p>Bounding Box Representation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*KjrFjAO0RfvUuyA_p3Th5g.jpeg" /><figcaption>bounding box representation.</figcaption></figure><ul><li>Here <strong>bx, by</strong> are the x,y center coordinates. we are passing our<strong> tx, ty</strong> values inside the sigmoid function to shrink them between 0–1 and then adding the <strong>cx,cy</strong> which are top-left coordinates of the cell grid. we are using sigmoid because if the prediction goes above 1 then the center of that bounding box might move into another cell grid which breaks the theory behind YOLO because if we postulate that the red box is responsible for predicting the object, the center of the object must lie in the current cell grid nowhere else. so we use a sigmoid to keep the center inside the cell grid itself.</li><li><strong>bw, bh </strong>is the width and height of our bounding box, if the predictions bx and by for the box containing the object are (0.3, 0.8), then the actual width and height on the 13 x 13 feature map are (13∗0.3, 13∗0.8).</li><li><strong>tx, ty, tw, th</strong> is what we got in our prediction.</li><li><strong>cx </strong>and <strong>cy </strong>are the top-left coordinates of the grid.</li><li><strong>pw </strong>and <strong>ph </strong>are anchors dimensions for the box. These pre-defined anchors are taken by running K-means clustering on a dataset.</li></ul><p><strong>multiscale output:</strong></p><p>in the above explanation, we only saw the prediction for the 13*13 feature map. same concepts will apply for 26*26 and 52*52 feature outputs by applying the transformation in different grid dimensions we are detecting different sizes of objects .in 13*13 grid we can detect very small objects whereas in 26*26 grid we can detect medium-sized objects and for the 52*52 grid we can detect a larger object and by concatenating the outputs we get the results of all three combined on a single image.</p><p>At each scale, each grid cell predicts 3 bounding boxes using 3 predefined anchors, making the total number of anchors used 9. (The anchors are different for different scales).</p><h4><strong>Non-maximum Suppression</strong></h4><p>so for an input image, the model predicts (52*52 +26*26 +13*13)*3 =10647 boxes, and that is a lot. to tackle this we drop the boxes whose Class Probabilities is less than 0.5 topically and we use the ‘<strong>Non-maximum Suppression’</strong> technique for the multiple bounding boxes surrounding the same object. to filter that out we use IOU(intersection over union) score which calculates how much overlap is there between actual and predicted boxes and use it to filter not-needed bounding boxes by comparing the actual bounding box and all the predicted bounding boxes for that particular object.</p><p>So, our required output shape is 13*13*425(5*(80+4+1)) where 5 is the number of anchor boxes, but we have the feature map of 13*13*1024. so to convert the feature to our desired output we simply use a 1 x 1 convolution layer to make this transformation.</p><p>13*13*1024 (feature map) — →(1*1*425 Conv) —→ 13*13*425(output)</p><p>Now our model is completed. now we can train it.</p><h3>Thank You</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79ad2937832" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/object-detection-state-of-the-art-yolo-v3-79ad2937832">Object Detection State of the Art-YOLO-V3</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chest X-Ray Medical Report Generation Using Deep Learning]]></title>
            <link>https://medium.com/analytics-vidhya/chest-x-ray-medical-report-generation-using-deep-learning-bf39cc487b88?source=rss-1c8634690d49------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf39cc487b88</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[encoder-decoder]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[image-captioning]]></category>
            <dc:creator><![CDATA[Sezaz Qureshi]]></dc:creator>
            <pubDate>Sun, 01 Nov 2020 18:27:41 GMT</pubDate>
            <atom:updated>2021-02-04T16:49:56.243Z</atom:updated>
            <content:encoded><![CDATA[<h3>Table of Contents:</h3><ol><li><em>Business Problem</em></li><li><em>Machine Learning problem</em></li><li><em>Exploratory Data Analysis</em></li><li><em>Machine Learning Model</em></li><li><em>Future work</em></li><li>References</li></ol><h3>1. Business Problem</h3><h3>1.1 Description</h3><p>If you go to the doctor with chest pain, a chest injury or shortness of breath, you will typically get a chest X-ray.The chest x-ray is the most frequently requested radiologic examination. The image helps your doctor determine whether you have heart problems, a collapsed lung, pneumonia, broken ribs, emphysema, cancer or any of several other conditions. Chest x-ray is also helpful in diagnosing COVID-19 infection in lungs , because COVID-19 is primarily attacks our lungs. Once you get your x-ray done your doctor will interpret it using his knowledge and instruct you further. So our aim is to make these x-rays easy to read by generating reports depicting what a radiologist sees and observes in x-ray.</p><p><strong>Problem Statement</strong></p><p>Build a deep learning model to generate medical report from given x-ray images.</p><p><strong>Data Source:</strong></p><p>PNG Images : <a href="http://academictorrents.com/details/5a3a439df24931f410fac269b87b050203d9467d">http://academictorrents.com/details/5a3a439df24931f410fac269b87b050203d9467d</a></p><p>XML Reports : <a href="http://academictorrents.com/details/66450ba52ba3f83fbf82ef9c91f2bde0e845ab">http://academictorrents.com/details/66450ba52ba3f83fbf82ef9c91f2bde0e845ab</a></p><h3>1.2 Real World / Business Objectives and Constraints</h3><ol><li>The cost of a misclassification can be very high.</li><li>No strict latency concerns.</li><li>Interpretability is partially important.</li></ol><h3>2. Machine Learning problem</h3><h3>2.1 Data</h3><h3>2.1.1 Data Overview</h3><ul><li><strong>Data will be in 2 TAR files extension:</strong></li></ul><ol><li>One folder will contain PNG images which will be x-rays.</li><li>Other one has XML reports(More than one image could be associated with a report)</li></ol><ul><li>Size of Posts.xml — 14.6GB Number of files in XML report folder = 3955</li><li>Number of files in XML report folder = 3955</li><li>Dataframe that we are using has 5 columns: ‘IMAGES’,’COMPARISON’,’INDICATION’,’FINDINGS’,’IMPRESSION’</li></ul><p><strong>Data Field Explanation</strong></p><ul><li>Dataset contains 3955 rows. columns in the table are:</li></ul><ol><li>IMAGES — contains paths of all the images related to a report(input variable)</li><li>COMPARISON — contains comments about different images of a report</li><li>INDICATION — contains description of why the x-ray was suggested.</li><li>FINDINGS — initial findings from the x-ray images.</li><li>IMPRESSION — detailed information about the x-ray(target variable)</li></ol><ul><li><strong>Number of Datapoints= 3955</strong></li></ul><h3>2.2 Mapping the real-world problem to a Machine Learning Problem</h3><h3>2.2.1 Type of Machine Learning Problem</h3><ol><li>This case study is basically based on generating a text given an input image. Specifically we want to generate a medical report given a chest x-ray image.</li><li>This falls under a Vision Language task , which is a mixture of computer vision domain and natural language processing domain.</li></ol><h3>2.2.2 Performance metric</h3><p>The metric that we will be using in this for evaluation will be BLEU score.</p><p>Bleu is a most common metric used for machine translation. It uses something called modified precision to calculate the score, this score lies between 0–1, 1 meaning it’s exactly the same or perfect and 0 means there is nothing in common.</p><p>As the term suggests the modified precision is used to overcome the normal<br>precision which is calculated as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/0*OfJfglDsFUCvq2wk.png" /><figcaption>precision</figcaption></figure><p>Candidate translation is the output/prediction of our model, Reference<br>translation is the input sentence that we have .<br>Let’s take an example and calculate the precision for the candidate<br>translation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/0*Ug4_6FG1SSEFUbUN.png" /></figure><p>The precision for candidate 1 is 2/7 (28.5%)<br>The Precision for candidate 2 is 1(100%).<br>But we know that these are not adequate results.<br>So we modify it as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*mBzLgWsCme2kyNUlhX7X-w.png" /><figcaption>Modified Precision</figcaption></figure><p>Here n-gram is the length of word to consider at a time where n is typically<br>taken to be 4. 1 gram will consider 1 word for each window, 2 gram will take<br>2 words and so on.<br>Count clip is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*EyqLpvBj4Gi73Q1laUjn_g.png" /><figcaption>count clip</figcaption></figure><p>We first calculate Count clip for any n-gram using the following steps :-</p><ul><li>Step1: Count the maximum number of times a candidate n-gram<br>occurs in any single reference translation; this is referred to as Count.</li><li>Step 2: For each reference sentence, count the number of times a<br>candidate n-gram occurs. As we have three reference translations, we<br>calculate, Ref 1 count, Ref2 count, and Ref 3 count.</li><li>Step 3: Take the maximum number of n-grams occurrences in any<br>reference count. Also known as Max Ref Count .</li><li>Step 4: Take the minimum of the Count and Max Ref Count. Also<br>known as Count clip as it clips the total count of each candidate word<br>by its maximum reference count</li><li>Step 5: Add all these clipped counts.</li></ul><p>Now just put the values and you will get modified precision, but what if the<br>translations are too long or too short??<br>Too long translations are by default handled by the modified precision score<br>by using count clipping.<br>For too short translations we introduce brevity penalty .<br>Brevity Penalty(BP) will be 1.0 when the candidate translation length is the<br>same as any reference translation length. The closest reference sentence<br>length is the “best match length.”</p><p>BP is an exponential decay and is calculated as shown below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*_x1MqVefYYqh81W0iP7rpA.png" /><figcaption>Brevity Penalty(BP)</figcaption></figure><p>r- count of words in a reference translation<br>c- count of words in a candidate translation</p><p><strong>Note : </strong>Neither the brevity penalty nor the modified n-gram precision length<br>directly considers the source length; instead, they only consider the range of<br>reference translation lengths of the target language.</p><p>Finally, we calculate BLEU</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*7IbLiFDkisprINiXtA6yrg.png" /><figcaption>Final BLEU score</figcaption></figure><p>BP- brevity penalty<br>N: No. of n-grams, we usually use uni-gram, bi-gram, 3-gram, 4-gram<br>Wn: Weight for each modified precision, by default N is 4, Wn is 1/4=0.25<br>Pn: Modified precision</p><p><strong>Reference Blog : </strong><a href="https://towardsdatascience.com/bleu-bilingual-evaluation-understudy-2b4eab9bcfd1">https://towardsdatascience.com/bleu-bilingual-evaluation-understudy-2b4eab9bcfd1</a></p><p>The BLEU score was proposed by Kishore Papineni, et al. in their 2002 paper “BLEU: a Method for Automatic Evaluation of Machine Translation“.</p><p><strong>link to Research paper:</strong> <a href="https://www.researchgate.net/publication/2588204_BLEU_a_Method_for_Automatic_Evaluation_of_Machine_Translation">https://www.researchgate.net/publication/2588204_BLEU_a_Method_for_Automatic_Evaluation_of_Machine_Translation</a></p><p><strong>We will use nltk library to calculate BLEU score.</strong></p><h3>3. Exploratory Data Analysis</h3><h3>3.1 Data Loading</h3><h3>3.1.1 Downloading data and extracting the TAR file</h3><p>Data is provided as a Torrent , so we will download Torrent to Google Drive Using Google Colab.</p><p>we can download torrent file with command line using <a href="https://transmissionbt.com/"><strong>Transmission </strong></a>client. which supports <strong>command line interface</strong>, all we have to do is install it and it will download our torrent file .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/504367d8be2874e95b6fd16f8e6c880a/href">https://medium.com/media/504367d8be2874e95b6fd16f8e6c880a/href</a></iframe><p>This will download install <a href="https://transmissionbt.com/"><strong>Transmission</strong></a><strong> </strong>BitTorrent client.</p><p>Then we will copy the torrent file link use transmission-cli to download torrent.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdb6326ee37738dc3c4c5f103a8b5d5c/href">https://medium.com/media/bdb6326ee37738dc3c4c5f103a8b5d5c/href</a></iframe><p>Above code will download the torrent file to my Google Drive from the given torrent file link.</p><p>Now that we have files, we have to extract it so we will use <a href="https://pypi.org/project/patool/"><strong>patoo</strong>l </a>library for that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57ce0bc1548bd55b3591e10547b50b0d/href">https://medium.com/media/57ce0bc1548bd55b3591e10547b50b0d/href</a></iframe><h3>3.1.2 Parsing the xml file</h3><p>Our reports are in xml files and we have to extract information from them.XML is an inherently hierarchical data format, and the most natural way to represent it is with a tree. It has two classes for this purpose — ElementTree represents the whole XML document as a tree, and Element represents a single node in this tree. Interactions with the whole document (reading and writing to/from files) are usually done on the ElementTree level. Interactions with a single XML element and its sub-elements are done on the Element level.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdb2c8bc20dbdad4d05e338633668ac3/href">https://medium.com/media/fdb2c8bc20dbdad4d05e338633668ac3/href</a></iframe><p>In the above piece of code we are going through each file in the directory and extracting ID, COMPARISON,INDICATION , FINDINGS,NAME_OF_IMAGES fields.</p><p>Now we will make Dataframe from these extracted columns, our initial dataframe has <strong>3955 data points.</strong></p><h3>3.2 EDA on each columns</h3><h4>3.2.1 COLUMN IMAGES:</h4><p>Images columns contain names of images associated with each report , more than one images could be associated with single report.</p><p>mean of number of images per report are : 1.8887484197218711<br>median of number of images per report are : 2.0<br>maximum number of images per report are : 5<br>minimum number of images per report are : 0</p><p>From the above evaluation we found out that we have maximum 5 images associated with a single report and we don&#39;t have any images associated for some reports in our data. the mean is closer to 2 and median is also 2 .</p><p>So lets have a look at number of images associated with each report.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*feQSq56JqEB0xrkuz5_khw.png" /><figcaption>number of words</figcaption></figure><ul><li>EDA on widths and heights:-</li></ul><p>Mean of heights: 531.6648922357829<br>Median of heights: 512.0<br>Mean of widths: 512<br>Median of widths: 512.0</p><h4>3.2.2 COLUMN COMPARISON:</h4><p>There are 2389 None or garbage values in our impression column. so it doesn&#39;t provide us with enough information. So we will drop this .</p><h4>3.2.3 COLUMN INDICATION:</h4><pre>Chest pain                               129<br>XXXX                                     114<br>Chest pain.                               88<br>NaN                                       86<br>chest pain                                62<br>XXXX.                                     58<br>XXXX-year-old female with chest pain.     39<br>XXXX-year-old male with chest pain.       38<br>Dyspnea                                   37<br>Shortness of breath                       31<br>dyspnea                                   29<br>Shortness of breath.                      23<br>XXXX-year-old female with chest pain      19<br>XXXX-year-old woman with chest pain.      19<br>XXXX-year-old female with XXXX.           19<br>Name: INDICATION, dtype: int64</pre><p>These are top 10 values that occur in indication column and i don&#39;t think these will prove of any value either so i am dropping it .</p><h4>3.2.4 COLUMN FINDINGS:</h4><p>Findings columns has 514 Nan columns, so if i drop these columns there will be lesser datapoints to build my model.So dropping this column too.</p><h4>3.2.5 COLUMN IMPRESSION(TARGET):</h4><p>Plotting top 20 impression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*29pweYFPb4aN92oqusu5sQ.png" /><figcaption>top 20 impressions</figcaption></figure><p>As we can see from above plot that there are very less Nan’s in impression column so instead of dropping them we will replace them with ‘no impression’ string.</p><p>Mean of words are in single impression are : <strong>10.493378343287457</strong><br>Median of words are in single impression are: <strong>5.0</strong><br>Maximum number of words are in single impression are : <strong>130</strong><br>Minimum number of words are in single impression are : <strong>1</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p1CdO56KPFze98U3gyWFDA.png" /><figcaption>Number of words in each sentence</figcaption></figure><p>So from the above we can observe that number of words in each impression lies between 2–30 , so we can expect short sentences from our model.</p><h3>Findings from EDA:</h3><ol><li>I think i will only keep the impressions and image columns others have many null values.</li><li>Mostly the reports are normal only some are abnormal so data bias is there.</li><li>Mainly there are 2 images per report so i will pass 2 images only, if less than that then i will repeat the 1st image itself twice. There fewer occurrences of 3 and 4 images per image i will keep first two and discard the rest.There is only one report with 5 images so will perform same actions as for 2–4 images.,</li></ol><h3>3.3 Data Cleaning</h3><p>Dropping columns as it has many null values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af80f1eef6401b76671067d0291935f6/href">https://medium.com/media/af80f1eef6401b76671067d0291935f6/href</a></iframe><h3>3.3.3 Most common words</h3><p>we will plot a word cloud which will show most occurring words , the font size is directly proportional with number of occurrence of that word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*el3si3cj8zM4HT_rPO9ZRA.png" /><figcaption>word cloud</figcaption></figure><h3>3.4 Data Preprocessing</h3><p>In this we will preprocess the input text in following ways:</p><ol><li>We will substitute ‘XXXX’ string which occur in many impression and has no meaning .</li><li>We will remove everything else small and capital alphabets .</li><li>Decontracting text: it is basically expand words from a contracted state, eg: won’t →will not, can’t → can not, etc.</li></ol><p>4. Converting tabs and extra spaces into single simple space.</p><h3>3.4.2 Preprocessing IMAGES column</h3><ol><li>Keeping only first two images per datapoints.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a9fe4b7f3125900ce15854f9c4cc5b1/href">https://medium.com/media/9a9fe4b7f3125900ce15854f9c4cc5b1/href</a></iframe><p>In above piece of code we are slicing each datapoint of our images columns which is a list of names of images and making its length 2 and then applying this operation to whole column</p><p>2. For rows having only one image per datapoint, we are copying that image twice.</p><h3>3.4.3 Adding special string to IMPRESSION column</h3><p>Inserting starting ‘&lt;start&gt;’ and ‘&lt;end&gt;’ string in impression column to let model know what is start and end of token , it will help while generating captions/impression.</p><p>We will make 3 new lists which will be as follows:</p><p><strong>ORIGINAL_SEQUENCE:</strong> &lt;start&gt; No acute pulmonary findings &lt;end&gt;<br><strong>INPUT_SEQUENCE:</strong> &lt;start&gt; No acute pulmonary findings <br><strong>OUTPUT_SEQUENCE:</strong> No acute pulmonary findings &lt;end&gt;</p><p>I will show use of this when building the model.</p><h3>3.4.4 Tokenizinzation.</h3><p>When working with text, the first thing we must do come up with a strategy to convert strings to numbers (or to “vectorize” the text) before feeding it to the model, thats when Tokenizer comes into play.</p><p>Tokenization is the process of converting word into integers where each word corresponds to a unique words all along the corpus.Tensorflow has tokenizer built in we just have to initialize that function and it will tokenize the input for us.</p><p>After we have tokenized out input sentences we have to make the size of all the inputs the same and for that we will pad the sequences ,padding can be done in two ways pre-padding(padding zeros at the start of the sequence ) or post-padding(padding zeros after the original sequence is over)</p><p>Initially i was limiting my max sequence length for padding to 99 percentile of word lengths i.e 53 of all the words in corpus , in the end I used 100 percentile i.e 123 ,so every sequence will have length of 123 and type of padding is post-padding.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80debe4093e4c3aa7d4363cbea6ba5b0/href">https://medium.com/media/80debe4093e4c3aa7d4363cbea6ba5b0/href</a></iframe><p>Sample after tokenization.</p><pre>sample input sequence [ 1 12 18 88  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0]</pre><pre>sample output sequence [12 18 88  2  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0 0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0 0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0<br>0  0  0]</pre><h3>4. Machine Learning Models</h3><h3>4.1 Split the data into train,validation and test.</h3><p>The first thing we will do is divide our data into train ,validation and test sets.We will use ‘<strong>sklearn </strong>’ train_test_split to split our data.</p><p>We will divide our dataset into train(90%), validation(9%), test(1%) of total data and shuffle it too.</p><p>Sklearn’s train_test_split will divide the data into only 2 parts(train and test) but we want validation too so we first divide data into 90%(train):10%(initial_test), and divide that 10% of initial test subset to 99.98%(validation) and 0.019%(final test) dataset.</p><p>I kept test size small because we just have to show few examples as output but greater validation data will help in training the model (indirectly, of course).</p><h3>4.3 Data augmentation</h3><p>Data augmentation is a process of generating slightly different copies of training data so as to make model’s performance stable over validation and test sets.</p><p>We are augmentation input images also because we don&#39;t have much data to train on.</p><p>So the next question is how will we apply augmentation to images while training?? the answer is simple before passing a image to the model we will apply any one random augmentation mentioned below. By doing this the model will see a augmented/different image every time it fetches a datapoint and thus it will help him in reducing overfitting and it can be well generalized .</p><p>The augmentation that we are using are:</p><ol><li>Flipping :flip images left to right or horizontally.</li><li>Flip images up down or vertically</li><li>Embosses images and overlays the result with the original image.</li><li>Detecting edges that have certain directions and marks them in a black and white image and then overlays the result with the original image.</li><li>Sharpening images</li></ol><p>To perform these mentioned augmentation on images we will use <a href="https://imgaug.readthedocs.io/en/latest/"><strong>imgaug</strong></a><strong> </strong>library.which is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b299237f2685f9b19ee8081351186c7/href">https://medium.com/media/9b299237f2685f9b19ee8081351186c7/href</a></iframe><h3>4.4 loading and preprocessing images</h3><p>To load and preprocess image we will use computer vision library called <a href="https://pypi.org/project/opencv-python/"><strong>opencv</strong></a><strong> .</strong></p><p>We will define a function which will load pre-process and augment an image when it is called and return the final image array.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cd30c043941582936c42b6b720b2b27/href">https://medium.com/media/3cd30c043941582936c42b6b720b2b27/href</a></iframe><p>In the above piece of code we are following the below steps.</p><ol><li>We are loading image using cv2.imread method</li><li>We are resizing the image as desired by the model using cv2.resize .</li><li>Then we are selecting a random number between 0–1 and applying any one augmentation accordingly.</li><li>At last we are normalizing image, which will compress/normalize the pixel values of image which ranges from 0–255 to 0–1 using cv2.normalize to make calculation simpler and computation faster.</li></ol><h3>4.5 Dataloader function:</h3><p>As the name suggests we are making a function which will inherit the functionality of <a href="https://www.tensorflow.org/api_docs/python/tf/keras/utils/Sequence">tf.keras.utils.Sequence</a> ,it is a safer way to do multiprocessing. This structure guarantees that the network will only train once on each sample per epoch which is not the case with generators.</p><p>Every Sequence must implement the __getitem__ and the __len__ methods. If you want to modify your dataset between epochs you may implement on_epoch_end. The method __getitem__ should return a complete batch.</p><p>Lets dive into each function of <strong>dataloader </strong>class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/960b493b310552ee310e9003dd37dad6/href">https://medium.com/media/960b493b310552ee310e9003dd37dad6/href</a></iframe><p>this function will define the length of dataloader.</p><p><strong>NOTE:</strong> when you call len(dataloader) it will return the length of dataloader not the length of training samples that you are passing in it. for eg: suppose you have 256 datapoints and your batch size is 8 so this function will return 256//8 which is 32 note 256.</p><p>2.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/612903fd29df41fcc1dbbe00766990d8/href">https://medium.com/media/612903fd29df41fcc1dbbe00766990d8/href</a></iframe><p>In this function we define what we want to do on epoch end , this function will be called after an epoch ends . We are just shuffling the indices of the datapoints after every epochs so that the models see different combination datapoints after every epoch.</p><p>3.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35245694a7af4161538c8310e0904ae2/href">https://medium.com/media/35245694a7af4161538c8310e0904ae2/href</a></iframe><p>This function will load the augmented, normalized image, we are calling calling load_image1 function which is same as preprocess_img function that I explained earlier.</p><p>4.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/abba262913baaea3d2aa3736f2a1d935/href">https://medium.com/media/abba262913baaea3d2aa3736f2a1d935/href</a></iframe><p>This is the function which loads the images ,input and output tensors in batches and return tuple of (input,target).</p><p>It takes start index as input and return batch output from that index, eg : if ‘i’ in the function is 4 and batch size is 16 then start index will be 4*16 till (4+1)*16 so it will take datapoints from 64–80 which is a batch of 16 . stack them and return them.</p><h3>4.6 Making model architecture.</h3><p>The model architecture that we are going to follow is called <strong>encoder-decoder </strong>model with attention mechanism.</p><p>The encoder-decoder models were initially developed for machine translation ,where both the encoder and decoder contains recurrent neural networks (LSTM,GRU) . The encoder part encodes the input sequence and then pass that processed information using its internal states to the decoder part of model, the decoder then process the input and generate translated output.</p><p>The problem with these models that the encoder output which was nothing but last lstm hidden and output states were not able to capture the crux of whole input sentence that was to be translated . To overcome this problem researchers introduced a way to to pass the information from encoder to decoder efficiently. that mechanism is called ‘<strong>Attention</strong>’ mechanism. This idea was introduced in the <a href="https://arxiv.org/abs/1409.0473">Neural Machine Translation by Jointly Learning to Align and Translate</a> paper back in 2015. We will get into the details of all the parts of the model in the upcoming section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PPTZFFcLniUYVU4mHWenPg.jpeg" /><figcaption>encoder-decoder model with attention</figcaption></figure><p>The above figure depicts the working of encoder-decoder models with attention mechanism on top of it.</p><p>We are modifying the encoder part and replacing it with the pre trained DenseNet121 model which is a convolution neural network instead of recurrent neural network , which will take image as an input and extract featuresor region of intrests and pass them further to attention mechanism.</p><p>To now lets dive into the parts of the model.</p><h3>4.6.1 Loading pre trained Chex-Net model.</h3><p>This model was introduced in <a href="https://arxiv.org/abs/1711.05225">CheXNet: Radiologist-Level Pneumonia Detection on Chest X-Rays with Deep Learning</a></p><p>In this experiment they took densenet121 which is a 121 layer convolutional neural network and initialized it with imagenet weights and trained it on <a href="https://arxiv.org/abs/1705.02315">ChestX-ray14 dataset</a> .They were trying to classify images into 14 classes or diseases based on the input images so it is a multi-label classification problem. the metric that they used is f1-score and compared the model’s performance on test data with the with 4 radiologists who manually labelled the diseases and the model outperformed them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/def4e32da429a46b0f7353aa3a0e64df/href">https://medium.com/media/def4e32da429a46b0f7353aa3a0e64df/href</a></iframe><p>We are using densenet121 and adding the pretrained weights of the Chex-Net model. we have to define the classes =14 because this model is trained on 14 class multi-label classification task. The image height and width that we took is <strong>(224,224,3)</strong> which is as same as what densenet default input shape is.</p><p><strong>weights_link</strong>: <a href="https://github.com/brucechou1983/CheXNet-Keras">https://github.com/brucechou1983/CheXNet-Keras</a></p><p>Once we load weights we are removing the last fully connected layers and global average pooling layer from the pre trained model. This leaves the output of last convolution block after concatenation or residual block and applying batch normalization and relu activation as our final output .Output of this model will act as a feature vector of our images.</p><h3>4.6.2 CNN_Encoder</h3><p>This is the Encoder block of our model inside this layer we will call our image feature extract model (chexnet) and reshape its output to make it look like the output of sequence to sequence encoder/LSTM (batch_size,hidden_state_size,units).</p><p>For example: Output of our image extract model is of shape(batch_size, 7, 7, 1024) from the lower convolution layer. we squash this input to (batch_size,49,1024) as output on encoder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/118b7eb8ca0db70926d9dba15710e601/href">https://medium.com/media/118b7eb8ca0db70926d9dba15710e601/href</a></iframe><h3>4.6.3 Attention:</h3><p>This is the part which will tell the lstm that which word to generate from which region of the image, that is why it is named as attention mechanism.</p><p>There are two types of attention mechanism’s .</p><ul><li><strong>Bahdanau Attention</strong></li></ul><p>This attention mechanism was introduced in the paper ‘<a href="https://arxiv.org/abs/1409.0473">Neural Machine Translation by Jointly Learning to Align and Translate</a>’ . It was introduced for sequence to sequence machine translation.lets have a look at the working in steps. lets assume we have a task of converting a sentence from English to French. so now we have tokenized and padded both the input and output texts for further use.</p><ol><li>Our English sentence will go inside the encoder part word by word as shown in the figure ‘<em>encoder-decoder model with attention’</em> above this steps are known as time steps .After that we will pass that input from an embedding layer that we will learn through backpropogation. after that each input goes inside the lstm unit and the hidden and output states of that lstm will change/update. This process will continue for each word.So when our input sentence ends we have the final LSTM hidden and output states as the output of our encoder.</li><li>So next comes the attention part, as of now we have lstm output states, hidden state and cell state as encoder output.</li><li>We will initialize our decoder model’s lstm with encoder hidden and cell state .</li><li>First the attention will take encoder output states and decoder hidden state as input. then it will compute similarity between them . by applying below shown operations these hidden and output states this will generate a similarity score.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/906ecfeb81d067fe259c7afe7fb830c9/href">https://medium.com/media/906ecfeb81d067fe259c7afe7fb830c9/href</a></iframe><p>5. Then we pass this score from a softmax function which will convert this score from range between 0–1. The shape of this similarities will be equal to hidden size of the encoder and we will call it attention weights because it will tell us how much attention it has given to each encoder hidden state in generating this output. Lets say, the the hidden size is 49 and the value at 31st index is <strong>0.88</strong> so we know that this has contributed more while generating the result because the probability will sum to 1 in the end by adding all the outputs due to softmax function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9aa2dc49a966cf54438a86218d762929/href">https://medium.com/media/9aa2dc49a966cf54438a86218d762929/href</a></iframe><p>6. then we multiply this attention weight with the encoder output states and add them to generate context vector for passing it to decoder lstm.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a49625cb94c6b054b0d4175d663078fb/href">https://medium.com/media/a49625cb94c6b054b0d4175d663078fb/href</a></iframe><ul><li><strong>Luong Attention</strong></li></ul><p>Luong’s attention is not much different from the Bahdanau Attention . the preocess is same . the major difference are:</p><ol><li>Luong introduces 3 techniques to calculate similarity score whereas bahdanau had only one method. these methods are shown in image below.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*kyxYIgqjdZLCUPObIzR_ww.png" /><figcaption>attetion types</figcaption></figure><p>Here score refers similarity , h_t is target hidden state and h_s is source output states, Wa and Va are weight matrices.</p><p>2. We have used Luongs concat attention method for our case study which is same as the Bahndanus attention similarity calculation.</p><p>3. After calculating the similarity score calculating attention weights and context vector are same as of bahndanau attention.</p><p>4. while calculating attention Bahndanus uses output of lstm which was generated in previous timestep, where Luong’s attention will use current timestep hidden state.</p><h3>4.6.5 Decoder</h3><p>Decoder is the the part of the model where translation happens, in our case the decoder contains embedding ,LSTM and a Dense layer(without any activation) at the end.</p><p>Decoder will take current word and generate next word at every step.lets have a look at the working of decoder step by step.</p><p>Remember in the tokenization we we made input_sequence and output_sequence differently, they will be used here, lets understand this with an example.</p><p><strong>ORIGINAL_SEQUENCE</strong>: &lt;start&gt; No acute pulmonary findings &lt;end&gt;</p><p><strong>INPUT_SEQUENCE</strong>: &lt;start&gt; No acute pulmonary findings</p><p><strong>OUTPUT_SEQUENCE</strong>: No acute pulmonary findings &lt;end&gt;</p><p>As we know the decoder will take input word by words, We use teacher forcing to decide the next input to the decoder.</p><p>Teacher forcing is the technique where the target word is passed as the next input to the decoder.</p><p>So the special token ‘&lt;start&gt;’ will go inside the decoder from INPUT_SEQUENCE and we expect ‘No’ as the output of the decoder which is also the first word in OUTPUT_SEQUENCE for the first timestep. after this the second word from INPUT_SEQUENCE which is ‘No’ will be the input to decoder and wee expect 2nd word from OUTPUT_SEQUENCE which is ‘acute’ as the output.</p><p>We initialize the hidden and cell state of decoder to a random numbers from normal distribution for every input sequence because the inputs are not related from image to image.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b9715b973a78e4a1c6ac10aa19335d3/href">https://medium.com/media/8b9715b973a78e4a1c6ac10aa19335d3/href</a></iframe><p>This is a function inside Decoder class named “one_step decoder” which will run for each time step i.e 123 times which is the max_sequence length that we decided while padding the inputs and perform the operation step by step as follows.</p><ol><li>It will take the first word from the INPUT_SEQUENCE pass it to the embedding layer. of predefined embedding dimensions which is 256 in our case.</li><li>Then the decoder hidden state from the previous time step along with encoder output states will be passed to the attention class what we explained above and it will return us the context_vector and attention weights (<strong>Note: </strong>we will not use attention weights while training only context vector will be used).</li><li>Now we will concatenate the context vector with the output of embedding and pass it to the lstm and we will initialize that lstm with previous timestep hidden and cell state . and generate current time step output,hidden and cell state.</li><li>We will pass the lstm output from a fully connected dense layer whose units will be same as vocab_size. Later we will extract the predicted word from the output of this dense layer.</li><li>We will return current step lstm output,its hidden state,its cell state and attention weights from this function.</li><li>For next step the the output received will be used as the input to the lstm as previous state hidden and cell state.This way the sequence information is retained inside the lstm cell of decoder.</li></ol><p>We will stack the output received from one_step_decoder function for each timestep and return it as the final encoder output.</p><h3>4.7 Loss Function and Optimizer</h3><p>We are using <a href="https://www.tensorflow.org/api_docs/python/tf/keras/losses/SparseCategoricalCrossentropy">Sparse Categorical Crossentropy</a> because of the way that we have encoded out true labels .</p><p>In normal Categorical Crossentropy these labels will be one hot encoded which is not the case for use we have tokenized the labels.</p><p>For eg:</p><p>y_true: [[1,0,0,0],[0,1,0,0],[0,0,0,1]] — As our true labels are single-label and we have multiclass classification problem we can also write this as.</p><p>y_true: [0,1,3] — It is nothing but the index of the true label.By encoding into this type we save a lot of memory while computing loss when the number classes are large because in the end the only one value will contribute to the loss term rest will become zero.</p><p>If you see we by using tokenizer we also have encoded our sentences into tokens like this only.</p><p>Each of these integers can be thought of as index where the particular value is one in one hot setting and the size of that particular array would be equal to vocabulary size.</p><p>As you have seen we have padded our sequences by adding zeros . these zeros should not interfere with the loss value so we have to find a way to overcome this problem to do this we will use sample_weight parameter of SparseCategoricalCrossentropy, this parameter let us define sample weight of each token, so first we will find if the token/label is zero if its not zero then we will assign its weight as 1 else the sample weight will be zero so these values wont disrupt our loss calculation.</p><p>The optimizer that we are using is <a href="https://www.tensorflow.org/api_docs/python/tf/keras/optimizers/Adam"><strong>Adam </strong></a>with learning rate of <strong>0.00001.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b60c7283c91fd7ba3124929d2d53313/href">https://medium.com/media/2b60c7283c91fd7ba3124929d2d53313/href</a></iframe><h3>4.9 Custom Training</h3><p>We have written our own custom loop, which is as follows.</p><ul><li>We will run for loop for n-number of epochs.</li><li>Inside that loop we will again iterate over our train dataloader using enumerate and we will receive batch_number ,inputs,target.</li><li>We will pass inputs and target into train_step function which will run our model for 1 batch/step ,calculate loss and apply gradient update.</li></ul><p>The train_step function does the following:</p><ol><li>First of all it will reset the hidden,cell states of the decoder.</li><li>It will pass image1 and image 2 array from our encoder part which will give us feature vector.</li><li>We then concatenate these feature vectors and add dropout to reduce overfitting.</li><li>We pass the input_sequence, concatenated features and decoder hidden,cell state which we initialized into the decoder.</li><li>The decoder will run for each time step internally and predict next word using image_features and input_sequence and return us the final prediction of that batch.</li><li>We will pass the decoder output and true output into our loss function .</li><li>We have to calculate loss for each token because when we compute gradient we want loss for each token .We add the loss for each token individually</li><li>We divide the calculated loss with the time step to get final loss of that batch.</li><li>We will then compute gradients and apply those gradients along with trainable variable to the optimizer.</li><li>In the end we will return total loss as output.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cba5eb6ba87f883054731ffe85f42eab/href">https://medium.com/media/cba5eb6ba87f883054731ffe85f42eab/href</a></iframe><ul><li>We get the loss of that batch then we add that loss to the total loss of the model .</li><li>When we compute the pass validation data into validation_Step. validation_step is same as train_step function except we don&#39;t update model weights in this step we just predict the output and report validation loss for model evaluation purpose.</li><li>After the completion of the epoch we save the losses by dividing the added loss to the total timesteps and we will shuffle indices of the train dataloader using on_epoch_end function inside that class.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f05bf33c38cef0a9a98fc4fe783a8949/href">https://medium.com/media/f05bf33c38cef0a9a98fc4fe783a8949/href</a></iframe><ul><li>Then we will use custom learning rate reducer, reduces learning rate if validation loss doesn&#39;t change for last 3 epochs</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75fbefecb6eadf0fdf21444d04db63a0/href">https://medium.com/media/75fbefecb6eadf0fdf21444d04db63a0/href</a></iframe><ul><li>We will implement custom early stopping callback which will check if there is no change in validation loss for 6 epochs it will stop the training.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28a612dbfe7d1da61243e538eedaf838/href">https://medium.com/media/28a612dbfe7d1da61243e538eedaf838/href</a></iframe><h3>4.10 Plotting losses</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*ErccyH2IWNAVLexXy1O7RQ.png" /><figcaption>loss diagram</figcaption></figure><h3>our model ran for <strong>34 </strong>epochs its training loss :<strong> 0.433114</strong> and val_Loss : <strong>0.387015</strong></h3><h3>4.11 model Evaluation</h3><p>Evaluate step is not much different from our train_step except we don&#39;t use teacher forcing here.</p><ol><li>We first pass input images that we have into the encoder and concatenate the output features.</li><li>We then initialize the hidden states and cell states of the decoder lstm.</li><li>Then we pass the token &lt;start&gt; which is our special token for to decoder which resemble the start of the prediction.</li><li>We will run the for loop for max_sequence_length.</li><li>Inside the for loop we call the one_step_decoder function of decoder class . by passing start token as decoder input, hidden and cell state and encoder output .</li><li>In return from that function we will receive prediction, new updated hidden , cell state of decoder lstm.</li><li>We pass all the three predicted word as decoder input hidden and cell state as previous time step outputs again to the one_step_decoder function to generate next word , this will continue till the range of max_seq_length.</li><li>We will save attention weights for plotting attention and use <strong>argmax </strong>of the predictions to find the predicted word.</li><li>We will stop our training in between, if special token&lt;end&gt; is predicted from our model.</li><li>This function will return resultant impression for image and attention weights for attention plot.</li></ol><h3>4.12 Model Predictions</h3><p>Before we see models prediction lets have a look at two functions</p><ol><li>Bleu_score : this function will give us 1,2,3,4-gram bleu score. we are using nltk’s bleu score for our use case.</li></ol><ul><li>Incorrect way of calculating BLEU score:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e84d38d4f902d6beccd43b1b707a4ee/href">https://medium.com/media/2e84d38d4f902d6beccd43b1b707a4ee/href</a></iframe><p>In above code reference refers to the correct translation or ground truth and translation refers as models, predicted output . When you pass the reference and translation as it is , this function will not throw an error but will give you good results instead, thats what happened to me i was getting total bleu score for whole data as 0.80 is very good but I thought that&#39;s something fishy about this score so i looked it up on their function implementation .</p><p>When you pass the function as it is it will break your sentence into letters not words , we have a limited vocabulary of 26 letters and there is a high chance that particular word occur in translated sentence too. that why it was giving me such a good score. Later i corrected it .</p><ul><li>Correct way of calculating BLEU score.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f20efe1eab8783c7d525b03cd468dbba/href">https://medium.com/media/f20efe1eab8783c7d525b03cd468dbba/href</a></iframe><p>See the difference between the wrong and correct one , this one takes list of reference/ground truth as there can be more than one reference sentences and each reference/ground truth is split into list of words too and for translation it takes list of words of translated sentence.</p><p>2. Plot_attention:</p><p>Phis function will take image , predicted sentence and attention weights as input and plot the attention.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4bcf8e0d1109d037a145071855a4b174/href">https://medium.com/media/4bcf8e0d1109d037a145071855a4b174/href</a></iframe><p>Here len_result is the length of predict string. we are iterating over it .</p><ol><li>First we are opening the images and then we are pasting them side by side by using function get_concat_h.</li><li>We are then iterating over the length of result .</li><li>We are first resizing the attention plot array into 7,7 array because this was the output of the last layer of the CHeXnet model 7,7,1024 then we resized into 49,1024 and then we concatenated the features which gave 49,2048. so now we are again separating it.</li><li>When we are adding subplots for plotting attention given at to each word.</li><li>We are setting the predicted word as the title of that subplot.</li><li>Then we are displaying images and then on top of it we are plotting our attention over the images and it will be displayed as grey color.</li></ol><h4><strong>some results:</strong></h4><ol><li><strong>result 1</strong></li></ol><pre>Real Caption: no acute cardiopulmonary findings chronic changes of emphysema and left basilar scarring<br>Prediction Caption: no hypoinflation minimal acute recommended lungs a left are identified no cannot &lt;end&gt;<br>BLEU score: 0.7071067811865476<br>Cumulative 1-gram: 0.250000<br>Cumulative 2-gram: 0.500000<br>Cumulative 3-gram: 0.632878<br>Cumulative 4-gram: 0.707107</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CyAY54P4wuR9Mp_hciH0gg.png" /><figcaption>attention plot1</figcaption></figure><p><strong>2. result2</strong></p><pre>Real Caption: no acute findings<br>Prediction Caption: no evidence have right nodules of chest &lt;end&gt;<br>BLEU score: 0.6147881529512643<br>Cumulative 1-gram: 0.142857<br>Cumulative 2-gram: 0.377964<br>Cumulative 3-gram: 0.526160<br>Cumulative 4-gram: 0.614788</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BU51u5zQNnW-0kkYenQYjw.png" /><figcaption>attention plot 2</figcaption></figure><p><strong>3. result 3</strong></p><pre>Real Caption: bilateral opacities most prominent in the lower lobes representing airspace disease or edema<br>Prediction Caption: retained volumes curvature normal lung prominent normal volumes fractures disease disease &lt;end&gt;<br>BLEU score: 0.5444358245099123<br>Cumulative 1-gram: 0.151591<br>Cumulative 2-gram: 0.355513<br>Cumulative 3-gram: 0.475026<br>Cumulative 4-gram: 0.544436</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gR2wrEw7UD9BF6DIfQgYZg.png" /></figure><h3>4.13 Final BLEU score for whole corpus.</h3><p>We have calculated the bleu score for whole corpus that we have and here are the results.</p><blockquote><strong><em>Final_bleau1_score 0.11377335230141303</em></strong></blockquote><blockquote><strong><em>Final_bleau2_score 0.20860306243858598</em></strong></blockquote><blockquote><strong><em>Final_bleau3_score 0.27927417083079303</em></strong></blockquote><blockquote><strong><em>Final_bleau4_score 0.3235168641768014</em></strong></blockquote><p>At the end the results are good :)</p><h3>5. Future work:</h3><ol><li>I would like to try <a href="https://arxiv.org/abs/1908.03557">VisualBERT: A Simple and Performant Baseline for Vision and Language</a> and <a href="https://arxiv.org/abs/2001.07966">ImageBERT: Cross-modal Pre-training with Large-scale Weak-supervised Image-Text Data</a></li><li>I would like try beam search for at model’s prediction tome to see if the results improve or not.</li><li>I would like to try different models for encoder part like yolov3,faster R-CNN, etc.</li></ol><h3><strong>6. REFERENCES :-</strong></h3><ol><li><a href="https://www.appliedaicourse.com/">www.appliedaicourse.com</a></li><li><a href="https://www.tensorflow.org/tutorials/text/image_captioning">https://www.tensorflow.org/tutorials/text/image_captioning</a></li></ol><h3>— Source Code for this blog .</h3><p><a href="https://github.com/sezazqureshi/chest-xray-medical-report-generation">sezazqureshi/chest-xray-medical-report-generation</a></p><h4>Have a look at my other case study too . I have made a search engine which is based on StackOverflow Questions and deployed it too on AWS. It will suggest you similar question based on your query .</h4><p><a href="https://sezazqureshi.medium.com/search-engine-based-on-stackoverflow-questions-2151307c283f">Search Engine Based on StackOverflow  Questions</a></p><h3>Do like and comment your views.</h3><h3>Thank you for Reading…</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf39cc487b88" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/chest-x-ray-medical-report-generation-using-deep-learning-bf39cc487b88">Chest X-Ray Medical Report Generation Using Deep Learning</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Search Engine Based on StackOverflow  Questions]]></title>
            <link>https://medium.com/analytics-vidhya/search-engine-based-on-stackoverflow-questions-2151307c283f?source=rss-1c8634690d49------2</link>
            <guid isPermaLink="false">https://medium.com/p/2151307c283f</guid>
            <dc:creator><![CDATA[Sezaz Qureshi]]></dc:creator>
            <pubDate>Sat, 03 Oct 2020 21:27:04 GMT</pubDate>
            <atom:updated>2021-02-20T17:57:59.926Z</atom:updated>
            <content:encoded><![CDATA[<h3>Search Engine Based on StackOverflow Questions</h3><h3>Table of Contents:</h3><ol><li><em>Business Problem</em></li><li><em>Machine Learning problem</em></li><li><em>Exploratory Data Analysis</em></li><li><em>Machine Learning Models : (BERT,DOC2VEC,WORD2VEC)</em></li><li><em>Future work</em></li><li>deployment on aws</li></ol><h3>1. Business Problem</h3><p><strong>1.1 Description</strong></p><p>Stack Overflow is the largest, most trusted online community for developers to learn, share their programming knowledge, and build their careers.<br> <br> Stack Overflow is something which every programmer use one way or another. Each month, over 50 million developers come to Stack Overflow to learn, share their knowledge, and build their careers. It features questions and answers on a wide range of topics in computer programming. The website serves as a platform for users to ask and answer questions, and, through membership and active participation, to vote questions and answers up or down and edit questions and answers in a fashion similar to a wiki or Digg. As of April 2014 Stack Overflow has over 4,000,000 registered users, and it exceeded 10,000,000 questions in late August 2015. Based on the type of tags assigned to questions, the top eight most discussed topics on the site are: Java, JavaScript, C#, PHP, Android, jQuery, Python and HTML.</p><p><strong>Problem Statement</strong></p><p>Build a search engine based on StackOverflow questions, the search results should include the semantic meaning.</p><p><strong>1.2 Source / useful links</strong></p><p>Data Source :<a href="https://archive.org/details/stackexchange">https://archive.org/details/stackexchange</a> <br> YouTube : <a href="https://youtu.be/nNDqbUhtIRg">https://youtu.be/nNDqbUhtIRg</a> <br> Research paper : Word2Vec <a href="https://arxiv.org/abs/1301.3781">https://arxiv.org/abs/1301.3781</a> <br> Research paper : Doc2Vec <a href="https://arxiv.org/abs/1405.4053">https://arxiv.org/abs/1405.4053</a> <br> Research paper : BERT <a href="https://arxiv.org/abs/1810.04805">https://arxiv.org/abs/1810.04805</a> <br> Research paper : Universal Sentence Encoder <a href="https://arxiv.org/abs/1803.11175">https://arxiv.org/abs/1803.11175</a> <br> word2vec Blog : <a href="https://blog.acolyer.org/2016/04/21/the-amazing-power-of-word-vectors/">https://blog.acolyer.org/2016/04/21/the-amazing-power-of-word-vectors/</a></p><h4>1.3 Real World / Business Objectives and Constraints</h4><ol><li>the search results should include the semantic meaning.</li><li>Think of scalable architecture and try to reduce the time to return the results.</li></ol><h3>2. Machine Learning problem</h3><h3>2.1 Data</h3><p>All of the data is in 1 zip-file: stackoverflow.com-Posts.7z <br> inside the zip file there will be one XML file : Posts.xml</p><pre><strong>Posts.xml</strong> contains 16 columns: Id,PostTypeId,AcceptedAnswerId,CreationDate,Score,ViewCount,Body,OwnerUserId,LastEditorUserId,LastEditDate,LastActivityDate,Title,Tags,AnswerCount,CommentCoun,FavoriteCount </pre><pre><strong>Size of Posts.xml</strong> - 14.6GB</pre><pre><strong>Number of rows in Posts.xml</strong> = 3 Million records</pre><p><strong>Note : </strong>we are not using this whole data for this case study, due to limited resources and time constraints</p><pre><strong>the dataframe that we are using has 3 columns: </strong> Id,title, Body</pre><pre><strong>Number of rows in dataframe</strong> = 112357</pre><p>-&gt; The questions are randomized and contains a mix of verbose text sites as well as sites related to math and programming. The number of questions from each site may vary, and no filtering has been performed on the questions (such as closed questions).</p><p><strong>Data Field Explanation</strong></p><p>Dataset contains 112357 rows. The columns in the table are:</p><pre><strong>Id</strong> - Unique identifier for each question</pre><pre><strong>Title</strong> - The question&#39;s title</pre><pre><strong>Body</strong> - The body of the question</pre><p>Id=”1&quot; <br> PostTypeId=”1&quot; <br> AcceptedAnswerId=”3&quot; <br> CreationDate=”2016–08–02T15:39:14.947&quot; <br> Score=”8&quot; <br> ViewCount=”436&quot; <br> Body=”&lt;p&gt;What does “backprop” mean? Is the “backprop” term basically the same as “backpropagation” or does it have a different meaning?&lt;/p&gt; “ <br> OwnerUserId=”8&quot; <br> LastEditorUserId=”2444&quot; <br> LastEditDate=”2019–11–16T17:56:22.093&quot; <br> LastActivityDate=”2019–11–16T17:56:22.093&quot; <br> Title=”What is “backprop”?” <br> Tags=”&lt;neural-networks&gt;&lt;backpropagation&gt;&lt;terminology&gt;&lt;definitions&gt;” <br> AnswerCount=”3&quot; <br> CommentCount=”0&quot; <br> FavoriteCount=”1&quot;</p><p>Id : “2214”</p><p>Title :</p><pre>&quot;When will the AI can replace developer or tester&quot;</pre><p>Body :</p><pre>&quot;&lt;p&gt;Now AI can replace call center, worker(in the factory) and going to replace court. When will the AI can replace developer or tester?&lt;/p&gt;</pre><pre>&lt;p&gt;I want to know how long can AI replace developer. e.g. next 10 years because...&lt;/p&gt;<br>&quot;</pre><h3>2.2 Mapping the real-world problem to a Machine Learning Problem</h3><pre>It is basically finding semantic similarity between documents.Here, the terminology “document” could refer to a web-page, a word document, a paragraph of text, an essay, a sentence, or even just a single word.  </pre><pre>Two semantically similar documents, will contain many of the same topics while two semantically different documents will not have many topics in common.  Machine learning methods are described which can take as input large collections of documents and use those documents to automatically learn semantic similarity relations.</pre><p><strong>Cosine similarity</strong> : Cosine similarity calculates similarity by measuring the cosine of angle between two vectors. This is calculated as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*cgMugPZQWQTU53giWq5cUw.jpeg" /></figure><p>link: <a href="https://en.wikipedia.org/wiki/Cosine_similarity">https://en.wikipedia.org/wiki/Cosine_similarity</a></p><h3>3. Exploratory Data Analysis</h3><h3>3.1.1 Downloading data and extracting the zip file</h3><p>i am using ‘cliget’ extension to get the data from the‘ archive.org’ through command line in my google-colab.</p><p>after that i am extracting the zip file using python library called <strong>patoolib.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35e07c4b37b67f4dd30d6b42110cdd7b/href">https://medium.com/media/35e07c4b37b67f4dd30d6b42110cdd7b/href</a></iframe><p>now that we have extracted the file , inside the zip file there will be one XML file : ‘ Posts.xml ’, we will parse that file and extract that the desired data from it.</p><p>to do that we will iterate through each row in the XML file ,the sample row is shown in section <strong>2.1.2.1 </strong>above .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f49451ec67ed21ef6274dbcf34a398f/href">https://medium.com/media/7f49451ec67ed21ef6274dbcf34a398f/href</a></iframe><p>we will check if the ‘postTypeId’ ==1 means question post and ‘postTypeId’ == 2 means answer post, we want only questions so we will filter it .and we will extract <strong>title </strong>and <strong>body </strong>from that row.</p><p>after this we will copy this data into the DataFrame under the columns title and body. and save this as .csv file for further use.</p><h3>3.2 Data Cleaning</h3><p>for this case study we will be using <strong>112357 data points.</strong></p><h3>3.2.1 Finding duplicate rows and removing them</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d96fbf2dcec30ea0d72a25add7f70427/href">https://medium.com/media/d96fbf2dcec30ea0d72a25add7f70427/href</a></iframe><p>now if there are any duplicate rows then we will remove them by using the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4c749137301de1cc4739aa4ca58e5c1/href">https://medium.com/media/a4c749137301de1cc4739aa4ca58e5c1/href</a></iframe><p>this will drop duplicates and will keep the first occurrence of the duplicate row.</p><p>here df is the name of the DataFrame that has our data.</p><h3>3.2.2 Checking whether there are any rows with null values</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e88b9822908513fc672815300f55784/href">https://medium.com/media/3e88b9822908513fc672815300f55784/href</a></iframe><p>Minimum length of the question : 20<br>Maximum length of the question : 34183</p><h3>3.2.4 Most common words</h3><p>We will be drawing <strong>word cloud</strong> for the most common words that occur in our Dataset, to do that we will first remove the stopwords(the words that occur too often eg :- is,an,the,a) from the corpus and then print the word cloud.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s3ubNfcDaLjHC52ujYlliA.png" /><figcaption>Word Cloud for Question</figcaption></figure><h3>3.3 Cleaning and preprocessing of Questions</h3><h3>3.3.1 Preprocessing</h3><p>preprocessing is basically cleaning the input corpus . the main aim of preprocessing is to remove redundant data and to make data suitable for machine learning models. The main steps that are included are:</p><p><strong>1. Separate out code-snippets from Body:</strong></p><p>in our input sentences the text contains the code also which is not needed as of now , the code section is in between &lt;code&gt; ….&lt;/code&gt; tags and we will remove this using regular expression library in python.</p><p><strong>2. Remove Special characters from Question title and description (not in code):</strong></p><p>we will remove all the special characters and and numbers , only keep words.</p><p><strong>3. Remove stop words (Except ‘C’):</strong></p><p>we will remove all the stopwords (stop words are those words which occur very often like:is, am, the, there..etc). we will keep the word c because its a programming language.</p><p><strong>4. Remove HTML Tags</strong></p><p>in this section we will remove all the HTML components from the data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e5c0bd7e5774a1eb43bf442e451802c/href">https://medium.com/media/4e5c0bd7e5774a1eb43bf442e451802c/href</a></iframe><p>in the above function we are using <strong>beautifulsoup </strong>library to remove parse the data using two parser (lxml and html5) ,lxml will search for XML tags and html5lib will search for HTML ones.</p><p>soup.get_text() will give us clean text .</p><p>after that we are substituting all the words inside the &lt;&gt; arrows, removing new line characters and removing div word.</p><p><strong>5. Convert all the characters into small letters:</strong></p><p>in this we will be converting our text into lower case so as to remove the redundancy.for example : New York → new york, I → i, ,etc.</p><p><strong>6. Use SnowballStemmer to stem the words:</strong></p><p>stemming is basically used for getting the root word by removing the stems from the word. for example :“likes”, “liked”,“likely”,“liking” will be converted to ‘’like’’.SnowballStemmer is present in the ‘nltk ’ library , a library which is popular for performing natural language processing tasks.</p><p>now we will all the steps in a single function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eff8dde20f2847e826577c49c4702702/href">https://medium.com/media/eff8dde20f2847e826577c49c4702702/href</a></iframe><p>so in above code snippet we are basically implementing what I said in above 6 steps.</p><p>first we are removing the code , after that removing the HTML tags after that we are merging title and body columns,then lowering the alphabets then performing stemming on them.</p><h3>3.3.2 Sample output after Preprocessing:</h3><p><strong>INPUT:</strong><br>&lt;p&gt;I have an absolutely positioned &lt;code&gt;div&lt;/code&gt; containing several children, one of which is a relatively positioned &lt;code&gt;div&lt;/code&gt;. When I use a &lt;code&gt;percentage-based width&lt;/code&gt; on the child &lt;code&gt;div&lt;/code&gt;, it collapses to &lt;code&gt;0 width&lt;/code&gt; on IE7, but not on Firefox or Safari.&lt;/p&gt;</p><p>&lt;p&gt;If I use &lt;code&gt;pixel width&lt;/code&gt;, it works. If the parent is relatively positioned, the percentage width on the child works.&lt;/p&gt;</p><p>&lt;ol&gt;<br>&lt;li&gt;Is there something I’m missing here?&lt;/li&gt;<br>&lt;li&gt;Is there an easy fix for this besides the &lt;code&gt;pixel-based width&lt;/code&gt; on the<br>child?&lt;/li&gt;<br>&lt;li&gt;Is there an area of the CSS specification that covers this?&lt;/li&gt;<br>&lt;/ol&gt;</p><p><strong>CLEAN OUTPUT:</strong></p><p>‘‘‘ percentag width child element absolut posit parent internet explor absolut posit contain sever children one relat posit use child collaps ie firefox safari use work parent relat posit percentag width child work someth miss easi fix besid child area css specif cover ’’’</p><h3>3.3.3 Converting preprocessed data into DataFrame and storing it as csv:</h3><p>now that we have the preprocessed data we will store it in a csv to use it further directly.</p><h3>4. Machine Learning Models</h3><p>Machine learning models take vectors (arrays of numbers) as input. When working with text, the first thing we must do come up with a strategy to convert strings to numbers (or to “vectorize” the text) before feeding it to the model.</p><p>The task that our models will try to solve will be vector-vector similarity, each model will predict the vectors and we will pass the query sentence as the vector(OF different size/dimension for different model) and compute the cosine similarity between them to find the most related/similar answer.</p><p>The word vectors are the vectors/arrays which tells the model about that particular word and how it is related to other words in the sentence.they are vector representations of a word/sentence. There are many ways of encoding words into vectors like: bag-of-words(This can be done by assigning each word a unique number. Then any document we see can be encoded as a fixed-length vector with the length of the vocabulary of known words. The value in each position in the vector could be filled with a count or frequency of each word in the encoded document.),tfidf(term frequency-inverse document frequency),etc. but these cannot capture semantic meaning of the sentence because they are simple and does not take order of words into account.</p><p>In our approach we will use word/sentence embeddings which contain the semantic meaning. Semantic meaning means it can learn relationships for eg: queen-king,man-woman will be closer ,and verb and tenses like walking-walked,swimming-swam will also be near to each other because they are very similar semantically.these vectors are of fixed size , more the dimensionality more information rich these word vectors/embeddings will be.</p><p><strong>Note:</strong></p><p><strong>for all our model we will judge their performance by single query sentence “what is superclass in object orient programming?”.</strong></p><h3>4.1 Split the data into test and train</h3><p>we will split out data into train and test for our machine learning models.</p><p>we will use ‘<strong>sklearn </strong>’ train_test_split to split our data with test size of 0.05%.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/506e604e1451d331d57fd1d1a51efdb5/href">https://medium.com/media/506e604e1451d331d57fd1d1a51efdb5/href</a></iframe><h3>4.2 Model-1 : BERT(Bidirectional Encoder Representations from Transformers):</h3><p>BERT (Bidirectional Encoder Representations from Transformers) provides dense vector representations for natural language by using a deep, pre-trained neural network with the Transformer architecture. It was originally published by</p><ul><li>Jacob Devlin, Ming-Wei Chang, Kenton Lee, Kristina Toutanova: <a href="https://arxiv.org/abs/1810.04805">“BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding”</a>, 2018.</li></ul><p>The TF Hub model uses the implementation of BERT from the TensorFlow Models repository on GitHub at <a href="https://github.com/tensorflow/models/tree/master/official/nlp/bert">tensorflow/models/official/nlp/bert</a>. It uses L=12 hidden layers (i.e., Transformer blocks), a hidden size of H=768, and A=12 attention heads.</p><p>This model has been pre-trained for English on the Wikipedia and Books Corpus using the code published on GitHub. Inputs have been “uncased”, meaning that the text has been lower-cased before tokenization into word pieces, and any accent markers have been stripped. For training, random input masking has been applied independently to word pieces (as in the original BERT paper).</p><p>for this assignment we will be using BERT from TensorFlow :</p><p><a href="https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/1">https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/1</a></p><p>BERT is a basically a part of the transformer model. The transformer is a encoder-decoder model. In BERT we use the encoder part of the transformer.</p><p>for this assignment we are using BERT base which has 12-identical encoder stacked at each other. lets see whats inside each encoder unit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*HaGTuYfNHWg45GZbTBnVSA.png" /><figcaption>single encoder unit</figcaption></figure><p>As we can see there are two parts inside this encoder unit</p><p>At first the feed forward neural network is the fully connected with 512 layers/units.This consists of two linear transformations with a ReLU activation in between.</p><p><strong>FFN(x) = max(0;xW1 + b1)W2 + b2 (2)</strong></p><p>While the linear transformations are the same across different positions, they use different parameters from layer to layer. Another way of describing this is as two convolutions with kernel size 1. The dimensionality of input and output is d = 512, and the inner-layer has dimensionality d’ = 2048.</p><p>second is self attention layer, which plays important role in giving attention to the words that are important and help the model to understand to context better.for eg: take the sentence</p><p><strong>&#39;</strong><strong>The animal didn&#39;t cross the street because it was too tired&#39;</strong></p><p>here <strong>it </strong>refers to what? animal or street?</p><p>it is simple for us humans to associate this with animal but for model to understand this it has to implement this self attention which will allow to associate it with animal.</p><p>so lets dive into the self attention part now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*RdvCpHss1tLvi6KO8vrBZA.png" /><figcaption>attention step 1</figcaption></figure><p>The <strong>first step</strong> in calculating self-attention is to create three vectors from each of the encoder’s input vectors (in this case, the pre-trained embedding of each word). So for each word, we create a Query vector, a Key vector, and a Value vector. These vectors are created by multiplying the embedding by these three matrices that we trained during the training process.</p><p>these vectors are of fixed size 64 as taken in the original paper.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*CHuDH2Ivg-RSnBu_ZGUw8A.png" /></figure><p>Look at the image above we have input <strong>thinking machines.</strong></p><p>Lets consider the first word ‘thinking’. first of all this input will be converted to the embedding of fixed length. after that we generate the three vectors as mentioned above. after that we will calculate the score by multiplying the query vector with all the key vectors (all the key vectors in the sentences before or after), after that the results of each multiplication is divided by square root of the dimensions of the keys vector which in our case is 8 because the dimension of keys vector is 64. after that we will pass the output of these numbers to a softmax function to generate/squash a score between 0–1.Then multiply these values(result of softmax) by ‘value vector’ and finally sum them up to produce the z1 vector for each word.</p><p>similarly we will calculate this z1 for all the words in the sentence.</p><p>the paper further refined the model by adding multi attention heads to expand the representational power of the model, in our case we are using 12 attention heads, so we will have 12 keys, values,queries matrices for each word.</p><p>The feed-forward layer is not expecting eight matrices — it’s expecting a single matrix (a vector for each word). So we need a way to condense these 12 down into a single matrix.</p><p>so we concatenate them and multiply them with another weight matrix to get the single matrix as output.</p><p>so the summary will look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PNdtPg2KINh9-lhrVswa0w.png" /><figcaption>attention summary</figcaption></figure><p>Since our model contains no recurrence and no convolution, in order for the model to make use of the order of the sequence, we must inject some information about the relative or absolute position of the tokens in the sequence. To this end, we add “positional encodings” to the input embeddings at the bottom of the encoder.</p><p>The input to the model is not only the embedding but the summation of two matrices one of which is embedding and second of which is positional embedding which is To give the model a sense of the order of the words, we add positional encoding vectors — the values of which follow a specific pattern.</p><p>We employ a residual connection around each of the two sub-layers, followed by layer normalization . That is, the output of each sub-layer is<br>LayerNorm(x + Sublayer(x)), where Sublayer(x) is the function implemented by the sub-layer itself. To facilitate these residual connections, all sub-layers in the model, as well as the embedding layers, produce outputs of dimension = 512. the figure below shows the full working of the single encoder block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*5fhAcRJSXEzVcirJcAxZSA.png" /></figure><p>If you want learn more about transformer and BERT refer this excellent blogs(the explanation that i have done is inspired from these blogs only) :</p><ol><li><a href="http://jalammar.github.io/illustrated-bert/">http://jalammar.github.io/illustrated-bert/</a></li><li><a href="http://jalammar.github.io/illustrated-transformer/">http://jalammar.github.io/illustrated-transformer/</a></li></ol><p>Now that we have learned all about BERT lets implement it.</p><h3>4.2.1 Loading the model</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfa08d39b8253bea61b25583c32a50af/href">https://medium.com/media/bfa08d39b8253bea61b25583c32a50af/href</a></iframe><p>In the above piece of code we have prepared the model which will take 3 inputs</p><ol><li>input_word_ids:- they are the input sentences encoded in the fixed and unique tokens, for each word in the input corpus there is a integer/token associated with it.the token length is fixed,200 in our case. if a sentence exceeds the 200 word/token limit the first 200 tokens are kept rest are cropped and if a sentence has less words then we use padding ,zeros are added till its length becomes max sequence length defined(200 in our case). we add [CLS] token at the start of each sentence and [SEP] token at the end of each sentence .</li><li>input_mask:- this input tells the model that how many real/padded tokens are there in the input_word_ids.its encoded as 1 for real tokens in input_word_ids 0 otherwise.</li><li>segment_ids:this one is useful when you are solving question answering dataset and you pass question and answer together to the model. in that case you will code all zeros for question tokens and all ones for answer tokens,but in our case there is only one sentence so we will make them all zeros.</li></ol><p><strong>Note:-</strong> all these arrays will be of fixed lengths , their sizes will be same as max_seq_length.</p><p>Code for input_tokens,input_mask,input_segment:-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb153cdb087664a3b1f0c7df71bcfd30/href">https://medium.com/media/fb153cdb087664a3b1f0c7df71bcfd30/href</a></iframe><p>Now for the output, there are two outputs: a pooled_output of shape [batch_size, 768] with representations for the entire input sequences. it is the output of the ‘[CLS]’ token that we add at the start of each sentence .</p><p>sequence_output of shape [batch_size, max_seq_length, 768] with representations for each input token (in context). for our case study we will use pooled output because it gives us the vector representation of the entire sentence in 768 dimensional vector.</p><p>This BERT model is pre-trained so we don&#39;t need to train it , we will directly predict the vector representation of the sentences by passing the sentence tokens, sentence mask,sentence segment to the model using model.predict.</p><h3>4.2.4 finding most similar document</h3><p>after we get the 768 vector representation of every word then we will compare it with the query word and return the most common sentence as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73c1ef58232fdf4bda9cd4f71009b9d4/href">https://medium.com/media/73c1ef58232fdf4bda9cd4f71009b9d4/href</a></iframe><p>So whats happening in the above code is first we are initializing the all the three arrays with zeros, then we are filling values by calling ‘tok ’ function that we showed above to get tokens,mask,segment. After that we will pass that to the BERT model to predict the output of the query word. after that we will compute cosine similarity between he predicted array and all the arrays that we have in our corpus .we will return top 5 or 10 results as list of strings.</p><h3><strong><em>top 5 results:</em></strong></h3><p><strong>prediction1:</strong> Custom view transition in OpenGL ES I’m trying to create a custom transition, to serve as a replacement for a default transition you would get here, for example:I have prepared an OpenGL-based view that performs an effect on some static texture mapped to a plane.</p><p><strong>prediction2 :</strong> Dynamic contact information data/design pattern: Is this in any way feasible?I’m currently working on a web business application that has many entities (people,organizations) with lots of contact information ie. multiple postal addresses, email addresses, phone numbers etc. At the moment the database schema is such that persons table has |</p><p><strong>prediction3:</strong> Databinding with Silverlight If I want to bind a collection to a some form of listing control in Silverlight. Is the only way to do it so make the underlying objects in the collection implement INotifyPropertyChanged and for the collection to be an Observablecollection? If I was using some sort of |</p><p>prediction 4 : SharePoint Default Styles I’m building a custom web part for SharePoint and I’m trying to use the default styles so when people theme the site, it will theme with it. I’ve found a couple of decent sites that show the different styles like: &lt;a href=”http://www.sharepointcustomization.com/resources/tipstricks/wss_cssguide.htm&quot; rel=”nofollow noreferrer”&gt;http://www.sharepointcustomization.com/resources/tipstricks/wss_cssguide.htm&lt;/a&gt;&lt;/p&gt; &lt;p&gt;but I’m looking for |</p><p><strong>prediction5: </strong>passing void to a generic class I’m trying to create a form that will animate something while processing a particular task (passed as a delegate to the constructor). It’s working fine, but the problem I’m having is that I can’t instantiate a copy of my generic class if the particular method |</p><h3>4.3 Model-2 : DOC2VEC MODEL</h3><p>for this case study we will be using genism’s Doc2Vec Model , this model is very similar to Word2Vec model, which we will discuss in next section. actually Doc2Vec model is an extension to Word2Vec model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VV7TQKbq9w8YrG1OeenxpA.png" /><figcaption>doc2vec architecture</figcaption></figure><p>This framework is similar to the CBOW architecture shown in word2vec section , the only change is the additional paragraph token that is mapped to a vector via matrix D. In this model, the concatenation or average of this vector with a context of three words is used to predict the fourth word. The paragraph vector represents the missing information from the current context and can act as a memory of the topic of the paragraph.</p><p>The paragraph token can be thought of as another word. It acts as a memory that remembers what is missing from the current context — or the topic of the paragraph. For this reason, we often call this model the Distributed Memory Model of Paragraph Vectors (PV-DM). The contexts are fixed-length and sampled from a sliding window over the paragraph. The paragraph vector is shared across all contexts generated from the same paragraph but not across paragraphs. The word vector matrix W, however, is shared across paragraphs. I.e., the vector for “powerful” is the same for all paragraphs.</p><p>PV-DM is same as CBOW algorithm ,which is mentioned in word2vec section in detail.</p><p>Matrix D has the embeddings for “seen” paragraphs (i.e. arbitrary length documents), the same way Word2Vec models learns embeddings for words. For unseen paragraphs, the model is again ran through gradient descent (5 or so iterations) to infer a document vector.</p><h3>4.3.1 preprocessing the sentences:</h3><p>first step of this model is to make data suitable for genims Doc2Vec implementation, this model takes list of tokens of string and unique tag as input.</p><p>so tokens here are words in a single document ,and tags will be just index number of that document in corpus.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f671cf160f481e77e990a8262434f87f/href">https://medium.com/media/f671cf160f481e77e990a8262434f87f/href</a></iframe><p>The above functions prepares the data for us as follows:</p><p>It takes two arguments: first is column of the DataFrame and second tokens_only which by default is False. the tokens_only is for test data to yield only tokens not tags.</p><p>First of all the function will iterate through each line in the corpus and generate tokens.To do that we will use genism’s ‘ simple_preprocess’ function which will first lowercase and then convert a document into a list of tokens.</p><p>Second now that we have list of tokens now so if tokens_only ==True it will just return the output of the simple_preprocess/ tokens.</p><p>Else, we will tag each document, to do that we will use gensim.models.doc2vec.TaggedDocument() function which will take tokens and unique tags as input and return tagged document as output. for us tags are nothing but line numbers so we will pass them along with the tokens to get tagged documents.</p><p>for train data we want tags and for test we just want list of tokens as input to predict that&#39;s why we are using two conditions.</p><p>now that we have data prepared we will initialize the model as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d1b28b4c1622a8bc7ff8dcc423c468f/href">https://medium.com/media/5d1b28b4c1622a8bc7ff8dcc423c468f/href</a></iframe><p>See its just one line of code to define a model in genism.</p><p>Now, lets understand each of the parameters.</p><ul><li><strong>vector_size :- </strong>dimensionality<strong> </strong>of the feature vectors.</li><li><strong>dm :- </strong>defines the training algorithm. If dm=1 means ‘distributed memory’ (PV-DM) and dm =0 means ‘distributed bag of words’ (PV-DBOW). Distributed Memory model preserves the word order in a document whereas Distributed Bag of words just uses the bag of words approach, which doesn’t preserve any word order.</li><li><strong>alpha :-</strong> The initial learning rate.</li><li><strong>min_alpha :-</strong> Learning rate will linearly drop to min_alpha as training progresses.</li><li><strong>min_count :- </strong>Ignores all words with total frequency lower than this.</li><li><strong>epochs :- </strong>Number of iterations (epochs) over the corpus.</li><li><strong>workers :- </strong>Use these many worker threads to train the model (=faster training with multi-core machines).-1 means use all available cores.</li></ul><h3>4.3.3 Building the vocabulary:</h3><p>Now that we have initialized our model we will build vocabulary of all the words in the training corpus by</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5cc057d1a37a27bdc1d92123ffe9471d/href">https://medium.com/media/5cc057d1a37a27bdc1d92123ffe9471d/href</a></iframe><p>Essentially, the vocabulary is a dictionary (accessible via model.wv.vocab) of all of the unique words extracted from the training corpus along with the count (e.g., model.wv.vocab[&#39;penalty&#39;].count for counts for the word penalty).</p><h3>4.3.4 Training the model:</h3><p>Now we will train our model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e449262a6f651de07bbdb28650756580/href">https://medium.com/media/e449262a6f651de07bbdb28650756580/href</a></iframe><p>We will train the model for 50 epochs .</p><h3>4.3.1 Finding the most similar doc:</h3><p>Now we will find the most similar document by providing a query word.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0aadf332eacb87ea9259d76229b61624/href">https://medium.com/media/0aadf332eacb87ea9259d76229b61624/href</a></iframe><p>So in the above piece of code we are first preprocessing our query sentence and then converting it to vector by predicting it from our train vector. by model.infer_vector() method.</p><p>Now that we have our sentence in vector format we will find most similar vector from the training corpus . To calculate distance/ similarity between the vectors genism by default calculates cosine similarity as a distance metric.</p><p>this will return us the list of tuples, inside of which first value is index of the document and second is cosine similarity between query and the document of which the index was provided in the first place.</p><h3>4.3.5 displaying result in pretty table:</h3><p>here are top 5 results :</p><ol><li>What is software development at your company really like (methodologies, tools, …)? Since I’ve started my first job as a professional software developer about two years ago, I’ve read many articles about commonly accepted methodologies (e.g. Scrum, XP), technologies (e.g. EJB, Spring), techniques (e.g. TDD, code reviews), tools (bug tracking, wikis) ,<strong>cosine_similarity:0.7261471748352051</strong></li><li>Best reference / crib sheet for AWK In a series of similar questions, what is the best AWK reference you’ve ever seen? If there isn’t really one (I’ve yet to find the grail), perhaps we could compile one in a separate question. ,<strong>cosine_similarity:0.7201393246650696</strong></li><li>control lost focus event when using keyboard shortcut For both .NET Winforms and Windows Presentation Foundation, if I have a text box that the user has just entered text into, and a button, if the user clicks the button the “LostFocus” event fires before the button click event fires. However if .,<strong>cosine_similarity:0.7175560593605042</strong></li><li>Best free Java .class viewer? I’ve used &lt;a href=”<a href="http://members.fortunecity.com/neshkov/dj.html">http://members.fortunecity.com/neshkov/dj.html</a>” rel=”noreferrer”&gt;DJ Java Decompiler&lt;/a&gt;, which has a handy GUI, but it seems as if the latest version is only a trial and forces you to purchase the software after some period of days (I recall using an earlier free version about a year .,<strong>cosine_similarity:0.6929471492767334</strong></li><li>How do I turn a python program into an .egg file? How do I turn a python program into an .egg file? .,<strong>cosine_similarity:0.69102257</strong></li></ol><p>i know the results are disappointing :’-(</p><p>so basically this model failed to capture the crux of a document in a single vector.</p><h3>4.4 Model-3 TFIDF- W2V</h3><p>First lets understand what is TFIDF.</p><p>Tf-idf stands for<em> term frequency-inverse document frequency</em>, and the tf-idf weight is a weight often used in information retrieval and text mining. This weight is a statistical measure used to evaluate how important a word is to a document in a collection or corpus. The importance increases proportionally to the number of times a word appears in the document but is offset by the frequency of the word in the corpus.it tends to give more importance to the less frequent words in the corpus.</p><p>Typically, the tf-idf weight is composed by two terms:</p><ul><li><strong>TF: Term Frequency</strong>, which measures how frequently a term occurs in a document. Since every document is different in length, it is possible that a term would appear much more times in long documents than shorter ones. Thus, the term frequency is often divided by the document length (aka. the total number of terms in the document) as a way of normalization:</li><li>TF(t) = (Number of times term t appears in a document) / (Total number of terms in the document).</li><li><strong>IDF: Inverse Document Frequency</strong>, which measures how important a term is. While computing TF, all terms are considered equally important. However it is known that certain terms, such as “is”, “of”, and “that”, may appear a lot of times but have little importance. Thus we need to weigh down the frequent terms while scale up the rare ones, by computing the following:</li><li>IDF(t) = log_e(Total number of documents / Number of documents with term t in it).</li></ul><p>See below for a simple example.</p><p><strong>Example:</strong></p><p>Consider a document containing 100 words wherein the word <em>cat</em> appears 3 times. The term frequency (i.e., tf ) for <em>cat</em> is then (3 / 100) = 0.03. Now, assume we have 10 million documents and the word <em>cat</em> appears in one thousand of these. Then, the inverse document frequency (i.e., idf ) is calculated as log(10,000,000 / 1,000) = 4. Thus, the Tf-idf weight is the product of these quantities: 0.03 * 4 = 0.12.</p><p>above example and definition is taken from :- <a href="http://www.tfidf.com/">http://www.tfidf.com/</a></p><p><strong>now lets come back to word2vec,</strong></p><p>as we discussed above <strong><em>word2vec</em></strong> is a algorithm that was proposed by <strong><em>‘Tomas Mikolov’</em></strong> and his team in research paper called in <a href="https://arxiv.org/abs/1301.3781">‘Efficient Estimation of Word Representations in Vector Space’</a>.</p><p>The main goal of his paper is to introduce techniques that can be used for learning high-quality word vectors from huge datasets with billions of words, and with millions of words in the vocabulary.</p><p>Main focus was to develop word embeddings which has multiple degrees of similarity , which means apart from words which are similar tends to be closer to each other.The model was also able to understand the complex relationships between the words.Somewhat surprisingly, it was found that similarity of word representations goes beyond simple<br>syntactic regularities. Using a word offset technique where simple algebraic operations are performed on the word vectors,</p><p>it was shown for example that vector(”King”) — vector(”Man”) + vector(” Woman”) results in a vector that is closest to the vector representation of the word Queen</p><p>We can see from the above example it ht embedding are so well that by performing simple addition and subtraction on vector results in a vector which is closely related to the result of these operations.</p><p><strong>In the paper milkov proposed two models for word2vec :</strong></p><ol><li><strong>CBOW(continuous bag of words)</strong></li><li><strong>skip-gram</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*OeAXz-OWSZHu1aQVLyTX6g.jpeg" /><figcaption>word2vec models</figcaption></figure><p>As we can see from the above figure both the models are opposite of one another.Both the models are trained using stochastic gradient descent and backpropagation</p><p><strong>Lets talk about CBOW first,</strong></p><p>CBOW main objective is to predict focus word given context words, for example if we have a sentence like ‘Raman is a good boy’, so all the words will first be encoded into one hot encoding,where the size of the one hot encoding vector will be the size of the vocabulary(vocabulary is the collection/dictionary of all the words that are present in the training corpus),so first our training dataset will be constructed like :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*-X6N42m1dDlcJmO9qyihjA.jpeg" /><figcaption>cbow dataset</figcaption></figure><p>but instead of the words there will be one hot encoding of these words as shown in word2vec models figure.</p><p>as we can see the data replication is done so the corpus size is much so less data is needed to train word2vec.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*L24Wdj_HCtWmIbyPhB5RzQ.jpeg" /><figcaption>CBOW ARCHITECTURE</figcaption></figure><p>As we can see above ,this problem can be seen as a <strong>multiclass classification problem</strong>,so first we encode our words in one hot encoding which will convert all our words into v-dimensional binary vectors where v is the size of vocabulary or the total number of words in our corpus, in that vector the index corresponding to that particular word will be 1 and others will all be zeros,</p><p>then we pass v-dim vectors to the hidden layer of the CBOW , this hidden layer is nothing but compose of N-linear activation function , which will pass the input as it is to the next layer.there are total N units of such functions which makes up this layer,and each and every input is connected to the layer N activation units.formula for that is as follows:</p><h3><strong>f(z) = z =w^t*x</strong></h3><p><strong>word2vec is not a deep learning algorithm because of this linear activation function, in deep learning models the activation functions are non linear so they can project complex relationships between vectors.</strong></p><p>where w is weight matrix is initialized as random numbers from Gaussian distribution they will be learned/updated through backpropogation.</p><p>if you want to learn about forward and backward propagation refer this blog.</p><p><a href="https://towardsdatascience.com/coding-neural-network-forward-propagation-and-backpropagtion-ccf8cf369f76">https://towardsdatascience.com/coding-neural-network-forward-propagation-and-backpropagtion-ccf8cf369f76</a></p><p>all the<strong> fully connected layers</strong> means that all the vectors from that layer are connected to the all the function of next layer.i have drawn single arrow just to make the diagram readable in reality these arrow will be connected to all the upcoming layer inputs, for eg take our fully connected layer 1 its size is of<strong> vx1</strong> , where v is number of rows and one column, and the next layer has N number of units so all ‘v ’vectors will be connected to all the ‘n ’units of the hidden layer and each of them will have weight corresponding to it.This weight as we discussed will be updated through back-prop.i have also shown a weight matrix in the diagram which is of shape (NxV),where,</p><p><strong>w2v(wi) = vec j</strong> , where j belongs N dimensions.</p><p>then this hidden layer is connected to a softmax layer, this softmax will give probability output for all v vectors and the probabilities will sum up to 1.</p><p>the formula for softmax function is :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*A-Oy1IF2JAxLWxG1lsFTAw.png" /><figcaption>softmax function</figcaption></figure><p>Where j is the word index which in our case is V and i is the number of total inputs to that function in our case its the inputs from hidden layer so k is N.</p><p>The output of this function will give us the probability of each predicted word, its probability so they all will sum to one(1), but the one the with the highest probability will be assigned as 1 and others as zeros we will do this using argmax function which will give us the index of the largest value. and we will set it as 1 and rest zero so the output will be also of V dimensional i.e one hot encoded.</p><p>then we will compare this output with the encoding of the correct word from our vocabulary and calculate the loss.</p><p>after that we will backpropogate and update the weights accordingly .</p><p>this process will be repeated until there is no major change in the weights and then we will stop the training the network and represent the results, which will be the weight matrix of the<strong> fully connected layer 5</strong> , which will be of shape <strong>(NxV)</strong> .so for every word in the vocabulary <strong>V , </strong>we have a fixed <strong>N</strong>-dimensional vector.</p><p><strong>now lets see skip-gram,</strong></p><p>It is exactly opposite of the CBOW model, we try to predict context words given focus word.so basically at the output it will have K-softmax layers, which means it will take more time and is computationally expensive</p><p>We use skip-gram when we have smaller dataset because it can work well this that and it is also useful in predicting infrequent words, the words which do not occur very often in our training corpus.In our case study we are using CBOW only so i will not bore you with the skip-gram model details.</p><h3>4.4.1 Converting sentences into list of sentences</h3><p>first of all we will convert our questions column into list of sentences to make it feasible for our word to vec model.</p><h3>4.4.2 Tfidf vectorization of sentences</h3><p>As you know we are using tfidf weighted word to vec ,for encoding our words into tfidf vectors we are using sklearns TfidfVectorizer .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c2ea870aa4544e0b8a51daddf769b65/href">https://medium.com/media/8c2ea870aa4544e0b8a51daddf769b65/href</a></iframe><p>In the above piece of code we are using tfidf vectorizer, the variable tfidf will contains matrix of shape(number of rows,number of tokens/unique words)</p><p>for each word it will contain the idf value of that particular word if it exist else it will be zero, so the matrix will be sparse.</p><p>In the dictionary variable we are storing all the tokens/feature names as keys and their corresponding idfs as values to use further .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d4360bd2d3d70d10474f1d082f6f507/href">https://medium.com/media/8d4360bd2d3d70d10474f1d082f6f507/href</a></iframe><p>Now we are defining our word 2 vec model , you can see its just one line of code the parameters are as follows:</p><ol><li><strong>sentences</strong>:- The sentences iterable can be simply a list of lists of tokens.</li><li><strong>min_count</strong>:- Ignores all words with total frequency lower than this.this will let us ignore less frequent words.</li><li><strong>size </strong>:- Dimensionality of the word vectors.</li><li><strong>workers</strong>:Use these many worker threads to train the model (=faster training with multi-core machines).</li><li><strong>iter</strong> (<em>int, optional</em>) — Number of iterations (epochs) over the corpus.</li><li><strong>sg</strong> (<em>{0, 1}, optional</em>) — Training algorithm: 1 for skip-gram; otherwise CBOW.(default)</li><li><strong>hs</strong> (<em>{0, 1}, optional</em>) — If 1, hierarchical softmax will be used for model training. If 0, and negative is non-zero, negative sampling will be used.</li></ol><p>We are training our own word2vec model rather than using pre-trained on google news one because it was giving good results than pre-trained model.</p><p>We chose vector size of 50 because of time constraint that we have , by using this size we were able to get results within 0.2 seconds and results were also very similar to the word2vec with vec size of 200,300.</p><p>Now as of this point we have our tfidf feature output and word2vec models output now we will combine them and generate tfidf weighted word2vec as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b39efc84a780a2977f8363e3314d1f7/href">https://medium.com/media/4b39efc84a780a2977f8363e3314d1f7/href</a></iframe><p>The above code is self explanatory, explanation is written in comments.</p><p>So basically we are first iterating over each word in the sentence and finding of that word is both present in wor2vec corpus and tfidf corpus, if yes then we are multiplying the tf_idf value of that word with the word2vec generated vector of that word. and summing them up till all the words in that sentence gets done.parallelly we are also summing up the tfi_idf values for each word. after the sentence is completed we are dividing the vector which was generated by multiplication of tfidf and word2vec with the tfidf-weight sum to make is <strong>tfidf_weighted_word2vec</strong>.</p><p><strong>here are top 5 results:</strong></p><p><strong>“Query : what is superclass in object orient programming”</strong></p><ol><li><strong>prediction1:-</strong> &quot;How to find if an object is from a class but not superclass In C how can you find if an object is an instance of certain class but not any of that class s superclasses is will return true even if the object is actually from a superclass”</li><li><strong>prediction2:- </strong>&quot;How would one write object oriented code in C What are some ways to write object oriented code in C Especially with regard to polymorphism See also Stack Overflow question Object orientation in C”</li><li><strong>prediction3:-</strong> &quot;Is Object Oriented Modeling different from Object Oriented Programming What is the difference between Object Oriented Modeling and Object Oriented Programming I overheard a conversation on my subway train this morning and it seems that these things are different Aren t they”</li><li><strong>prediction4:-</strong> &quot;Object orientation in C What would be a set of nifty preprocessor hacks ANSI C ISO C compatible which enable some kind of ugly but usable object orientation in C I am familiar with a few different object oriented languages so please don t respond with answers like Learn C”</li><li><strong>prediction5:-</strong> &quot;Is JavaScript object oriented There have been some questions about whether or not JavaScript is an object oriented language Even a statement just because a language has objects doesn t make it OO Is JavaScript an object oriented language”</li></ol><p>Here at the end, results are good enough.</p><h3><strong><em>5. Future work:</em></strong></h3><ol><li>I would like to try Universal Sentence Encoder.although it uses bert as one of its models, it should work well.</li></ol><p>Paper: <a href="https://arxiv.org/abs/1803.11175">https://arxiv.org/abs/1803.11175</a></p><p>TF-HUB Model: <a href="https://tfhub.dev/google/universal-sentence-encoder-lite/2">https://tfhub.dev/google/universal-sentence-encoder-lite/2</a></p><p>2. I would like to try fasttext also.</p><p>Paper:<a href="https://research.fb.com/downloads/fasttext/">https://research.fb.com/downloads/fasttext/</a></p><p>3. I would like to try all these with larger data corpus, as of now i am considering only 1.2 lac data points , i would like to try it with 5–6 lac data points in future and see the results.</p><h3><strong>— Source Code for this blog .</strong></h3><p><a href="https://github.com/sezazqureshi/stackoverflow-search-engine">sezazqureshi/stackoverflow-search-engine</a></p><h3>6. deployment on aws</h3><p>I have deployed a my search engine with <strong>aws </strong>,have a look and search for results on you own:</p><p><strong>SatckOverflow Search Engine link:</strong></p><p><a href="http://ec2-3-137-138-82.us-east-2.compute.amazonaws.com:8282/index">http://ec2-3-137-138-82.us-east-2.compute.amazonaws.com:8282/index</a></p><p>THANK YOU FOR YOUR TIME :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2151307c283f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/search-engine-based-on-stackoverflow-questions-2151307c283f">Search Engine Based on StackOverflow  Questions</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>