<?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 Gayathri s on Medium]]></title>
        <description><![CDATA[Stories by Gayathri s on Medium]]></description>
        <link>https://medium.com/@abhi.gayathri1997?source=rss-439ba5e2de57------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*mB85RGF9gK1bKpxt.</url>
            <title>Stories by Gayathri s on Medium</title>
            <link>https://medium.com/@abhi.gayathri1997?source=rss-439ba5e2de57------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 12:49:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abhi.gayathri1997/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[Use Transfer learning in BERT model to predict correct descriptive answer for open-ended questions]]></title>
            <link>https://medium.com/analytics-vidhya/use-transfer-learning-in-bert-model-to-predict-correct-descriptive-answer-for-open-ended-questions-e2c4d94e6098?source=rss-439ba5e2de57------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2c4d94e6098</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[transfer-learning]]></category>
            <category><![CDATA[bert]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <dc:creator><![CDATA[Gayathri s]]></dc:creator>
            <pubDate>Fri, 01 Nov 2019 17:39:06 GMT</pubDate>
            <atom:updated>2019-11-23T17:02:28.919Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*xYMMOXcU3KHXJO7Bx2Bz_w.jpeg" /></figure><p>An <strong>open-ended question</strong> is a question that cannot be answered with a “yes” or “no” response, or with a static response. Open-ended questions are phrased as a statement which requires a response. The response can be compared to information that is already known to the questioner.</p><p>Examples of open-ended questions:</p><ul><li>Tell me about your relationship with your supervisor.</li><li>How do you see your future?</li><li>Tell me about the children in this photograph.</li><li>What is the purpose of government?</li><li>Why did you choose that answer?</li></ul><h3>Problem</h3><p>The problem is a simple questions and answer problem where the we have to predict whether an answer is correct for a given question or not but the cache here is that the answers are descriptive.For a given questions, there are 10 answers out of which 9 are incorrect and 1 is correct. An Example of a question and answers set is:</p><blockquote><strong>1) symptoms of air pollution exposure ?</strong></blockquote><blockquote><strong>Answer 1: </strong>Long-term exposure to polluted air can have permanent health effects such as: 1 Accelerated ageing of the lungs. 2 Loss of lung capacity and decreased lung function. 3 Development of diseases such as asthma, bronchitis, emphysema, and possibly cancer. 4 Shortened life span.</blockquote><blockquote><strong>2) symptoms of air pollution exposure ?</strong></blockquote><blockquote><strong>Answer 2: </strong>Long-term exposure to particulate pollution can result in significant health problems including: 1 Increased respiratory symptoms, such as irritation of the airways, coughing or difficulty breathing. 2 Decreased lung function. 3 Aggravated asthma. 4 Development of chronic respiratory disease in children.</blockquote><blockquote><strong>3) symptoms of air pollution exposure ?</strong></blockquote><blockquote><strong>Answer 3: </strong>Short-term effects of air pollution on health. It is possible that very sensitive individuals may experience health effects even on Low air pollution days. Use the Daily Air Quality Index to understand air pollution levels and find out about recommended actions and health advice. The advice here applies to anyone experiencing symptoms. Short-term effects. Air pollution has a range of effects on health. However, air pollution in the UK on a day-to-day basis is not expected to rise to levels at which people need to make major changes to their habits to avoid exposure; Nobody need fear going outdoors, but they may experience some noticeable symptoms depending on which of the following population groups they are in:</blockquote><blockquote><strong>4) symptoms of air pollution exposure ?</strong></blockquote><blockquote><strong>Answer 4: </strong>Long-term exposure to particulate pollution can result in significant health problems including: Increased respiratory symptoms, such as irritation of the airways, coughing or difficulty breathing Decreased lung function</blockquote><blockquote><strong>5) symptoms of air pollution exposure ?</strong></blockquote><blockquote><strong>Answer 5: </strong>Long-term exposure to polluted air can have permanent health effects such as: Accelerated ageing of the lungs; Loss of lung capacity and decreased lung function; Development of diseases such as asthma, bronchitis, emphysema, and possibly cancer; Shortened life span</blockquote><blockquote><strong>6) symptoms of air pollution exposure ?</strong></blockquote><blockquote><strong>Answer 6: </strong>Short-term exposure to particulate pollution can: Aggravate lung disease causing asthma attacks and acute bronchitis; Increase susceptibility to respiratory infections; Cause heart attacks and arrhythmias in people with heart disease; Even if you are healthy, you may experience temporary symptoms, such as: Irritation of the eyes, nose and throat; Coughing</blockquote><blockquote><strong>7) symptoms of air pollution exposure ?</strong></blockquote><blockquote><strong>Answer 7: </strong>Children with asthma may notice that they need to increase their use of reliever medication on days when levels of air pollution are higher than average. Adults and children with heart or lung problems are at greater risk of symptoms. Follow your doctor’s usual advice about exercising and managing your condition. It is possible that very sensitive individuals may experience health effects even on Low air pollution days. Anyone experiencing symptoms should follow the guidance provided.</blockquote><blockquote><strong>8) symptoms of air pollution exposure ?</strong></blockquote><blockquote><strong>Answer 8: </strong>Long-term exposure to polluted air can have permanent health effects such as: Accelerated ageing of the lungs. Loss of lung capacity and decreased lung function. Development of diseases such as asthma, bronchitis, emphysema, and possibly cancer.</blockquote><blockquote><strong>9) symptoms of air pollution exposure ?</strong></blockquote><blockquote><strong>Answer 9: </strong>Your actual risk of adverse effects depends on your current health status, the pollutant type and concentration, and the length of your exposure to the polluted air. High air pollution levels can cause immediate health problems including: 1 Aggravated cardiovascular and respiratory illness. 2 Added stress to heart and lungs, which must work harder to supply the body with oxygen. 3 Damaged cells in the respiratory system.</blockquote><blockquote><strong>10) symptoms of air pollution exposure ?</strong></blockquote><blockquote><strong>Answer 10: </strong>Exposure to such particles can affect both your lungs and your heart. Long-term exposure to particulate pollution can result in significant health problems including: Increased respiratory symptoms, such as irritation of the airways, coughing or difficulty breathing; Decreased lung function; Aggravated asthma</blockquote><p>Out of all these answers, 9th one is the correct answer. For all the correct questions, the label predicted must be 1 and for all the wrong answers, the labels predicted must be 1. Thus it is a <strong>binary classification </strong>problem.</p><h4>Challenge</h4><p>But some of the challenges in solving the problems are:</p><ul><li>Highly imbalanced data. For one correct answer, there are 9 wrong answers.The imbalance ratio is 9:1.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XZ02sTW0jwYnysLdYjZtMA.png" /><figcaption>plot showing distribution of correct and wrong answer classes in the dataset</figcaption></figure><ul><li>No scope for feature engineering. Since each question is distinct and unique, there is no scope of any feature engineering that can be done</li></ul><p>These challenges are need to be overcome while solving the problem.</p><h3>Approach</h3><h4>1) Data Cleaning</h4><p>Simple data processing technique done is done such as</p><ul><li>Removal of HTML</li></ul><p>Removal of some of the html tags and entities such as &lt;p&gt;,&lt;a&gt;, &amp;nbsp;</p><pre>import re<br>#function to clean the word of any html-tags and make it lower case<br>def cleanhtml(sentence): <br>    cleanr = re.compile(&#39;&lt;.*?&gt;&#39;)<br>    cleanentity = re.compile(&#39;&amp;.*;&#39;)<br>    cleantext = re.sub(cleanr, &#39; &#39;, sentence)<br>    cleantext = re.sub(cleanentity, &#39; &#39;, cleantext)<br>    return cleantext.lower()</pre><ul><li>Removal of URLs</li></ul><p>Since URL too has a special structure, normal data processing treatment will make it loose its meaning, also URLs doesn’t carry any significant meaning, hence removing it makes data effective</p><pre>url_regex = &#39;http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&amp;+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+&#39;;</pre><pre>for i in range(preprocessed_questions.shape[0]):<br>    preprocessed_questions[i] = re.sub(url_regex, &#39;&#39;, preprocessed_questions[i]);</pre><ul><li>Removal of punctuation etc</li></ul><p>Punctuation such as ;%&amp; should be removed as they don’t carry significant meaning.Also the isn’t, haven’t etc are expanded as is not, have not etc</p><pre>#function to clean the word of any punctuation or special characters<br>def cleanpunc(sentence): <br>    cleaned = re.sub(r&#39;[?|!|&quot;|#|:|=|+|_|{|}|[|]|-|$|%|^|&amp;|]&#39;,r&#39;&#39;,sentence)<br>    cleaned = re.sub(r&#39;[.|,|)|(|\|/|-|~|`|&gt;|&lt;|*|$|@|;|→]&#39;,r&#39;&#39;,cleaned)<br>    return  cleaned</pre><p>Here, we have specifically omitted removal of stop words process due to certain reasons that will is revealed in later section.</p><h4>2) Metrics Used</h4><p>Considering that the data is highly imbalanced one, the metrics should also be the one that accommodates this fact. Hence the metrics chosen are</p><ul><li>Confusion matrix</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*fA8e2fMtCe1RG__lSjWWTQ.png" /><figcaption>Confusion matrix</figcaption></figure><ul><li>precision</li><li>recall</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*9aXOI8S07MbQgkqAMG8Wyg.png" /></figure><ul><li>F1-score</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*c5cm1z_gDRQnAACQNdvbBQ.png" /></figure><p>F1-score is used as it will be high only when precision and recall is high.</p><p>Accuracy is not a preferred metric here as the there is a high imbalance in data. Confusion matrix is also used here we must know the correctly and wrongly predicted number of data points in each of the class</p><ul><li>Mean Reciprocal Rank</li></ul><p>Mean Reciprocal rank is the computed as follows:<br>1) Each questions has 10 possible answers and any one of them are correct.Hence we take the probability of the all those ten answers being a correct one.<br>2) We sort those probabilities and assign rank to each of the answers. The answer with highest probability gets rank one, second highest with rank 2 and so on.<br>3) We take the rank of the correct answer in it and take the reciprocal of the rank.Like this we add up the reciprocal rank of all the correct answers</p><p>The idea is that we want all the correct answers to get a higher rank, rank 1 ideally.<br>Ideal MRR value is 1 and a very poor MRR will be 0.</p><pre>#Calulates the rank of the correct answer for each question based on the sorted order of its probability</pre><pre>#Takes the inverse of that rank and adds it together</pre><pre>def mrr(y_pred, y_true):<br>    count = 0<br>    mean_reciprocal_rank = 0<br>    while y_pred.shape[0]:<br>        y_pred_chunk = y_pred[0:10]<br>        y_pred = y_pred[10:]<br>        y_true_chunk = y_true[0:10]<br>        y_true = y_true[10:]<br>        y_true_array = np.argmax(y_true_chunk, axis=1)<br>        try:<br>            index_of_correct_answer = y_true_array.tolist().index(1)<br>        except Exception as e:<br>            continue<br>        prob_of_correct_answer = y_pred_chunk[index_of_correct_answer]<br>        sorted_prob_pred = np.array(sorted(y_pred_chunk, key=lambda x:(-x[1])))  <br>        sorted_prob_pred = np.array(sorted(sorted_prob_pred, key=lambda x:(x[0])))<br>        for rank in range(10):<br>            if (sorted_prob_pred[rank][0] == prob_of_correct_answer[0] and sorted_prob_pred[rank][1] == prob_of_correct_answer[1]):<br>                break<br>        rank = rank+1<br>        mean_reciprocal_rank += (1/rank)<br>        count = count+1<br>    return mean_reciprocal_rank/count</pre><h4><strong>3) Technique Used</strong></h4><p>The Machine learning technique used to solve this problem is deep learning.</p><h4><strong>Why use Deep Learning ?</strong></h4><p>The main reasons to choose deep learning to solve this problem is:</p><ul><li>The problem doesn’t require interpretability and latency as constraints. Had these constraints<strong> </strong>been there it using deep learning techniques would not be a right option as deep learning model requires input being passed to all its layers takes a lot of time to make the label prediction and there is no notion of interpretability in deep learning as they are complex models</li><li>No feature engineering seems to be possible for the problem. Hence a deep learning technique which automatically learns features from the data will be very helpful for the problem.</li></ul><h4>Why BERT ?</h4><p>Several Neural network architecture are tried such as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*S_XqQo-1OpIQK23rayXVmQ.png" /><figcaption>Neural network with 5 hidden layers</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*vGH0dIof7OuwzpMG6wa8qw.png" /><figcaption>Neural network with four 1-Dimensional convolutional network</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*h_FFaZGwjmQU0roY69Qupw.png" /><figcaption>Neural network with both 1-dim convolutional layer and LSTM layers</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*PyF8-NxYuC772UViHaPw9g.png" /><figcaption>Neural network with LSTM Layers and time distributed dense layers</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*Km-iZpAG-9KSaD5gKDJ3VA.png" /></figure><p>First four models are trained with two types of embeddings of the data:</p><ol><li>Glove vectors</li><li>TF-IDF Weighted Glove vectors</li></ol><p>The fifth layer is has a data embedding layer which does embedding for the data as part of learning.But none of them worked. Even hyper-parameter tuning and increasing the data size didn’t increase. The prediction results for class 1 still is very poor and all the model trained are dumb models since the problem is much harder to be solved by these simple architectures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*6wLRnDdqSf3resK00NJnxw.png" /><figcaption>Confusion matrix obtained</figcaption></figure><p>Since there is a huge class imbalance, the neural networks are trained by assigning class weights to balance the imbalance.</p><p>The prediction results for class 1 is little better but that was at the cost of the prediction of class 0. We can observe a tug of war like happening between class 0 and 1.Though the predictions for class 1 is pretty good that has indeed affected the predictions of class 0</p><p>Each of the neural network is connected with tensor board to dive deep into the problem.On investigating the tensor board histogram plot of the gradients, we could observe that most, nearly all of the gradients are of correct values in the sense that they are neither too small nor too large.Hence we could conclude that the networks did not run into vanishing or exploding gradient problems.May be the network are not too powerful to learn such a complex problem<br><br> Also on inspecting the MRR of each of the network, we can observe that it gives a very low MRR (of 0.33) meaning many of the wrong answer dataset is wrongly predicted as correct answer label which is because most of the wrong answers are being predicted as correct and some of the correct answers have a very low rank( means predicted with very less probability<br>compared to the other co wrong answers</p><p>We can go on and try and experiment different architecture that would work for this problem but that would be computationally expensive. It requires a lot of computational power to train and experiment with these problems.</p><p>Here is where transfer learning saves the day. Instead of trying multiple architectures as it is computationally intensive, it is best to use transfer learning and fine tune a pre trained NLP model to solve this problem. BERT is the state of the art NLP model conceived by google and hence BERT is chosen for transfer learning</p><h4>4) BERT</h4><p>BERT (Bidirectional Encoder Representations from Transformers) is the recent paper published by Google and is currently the state of the art technique for all NLP models.T he major innovation in the BERT being its attention technique where it masks few of the words in the input and try to predict it from the context information which is the words around it and contrast to the previous NLP model which processes data from left to right, it processes input from both left to right and right to left.</p><p>Pytorch provides a pre-trained BERT model which is fine-tuned for our data .The model is trained in the google colab by using its GPU.</p><p>To train any deep learning model with the google colab GPU, open your jupyter notebook in google colab and click <strong>EDIT → NOTEBOOK SETTINGS </strong>and then on the ensuing dialog box, select GPU as the hardware accelerator and then click <strong>SAVE</strong>.</p><pre>model = BertForSequenceClassification.from_pretrained(&quot;bert-base-uncased&quot;, num_labels=2)<br>model.cuda()</pre><p><strong>Input Format:</strong></p><p>The input is fed in the in the form of “questions ? answers” to the BERT. This technique worked better than the simple concatenation of questions and answer when training a bert model and hence this is used.</p><p><strong>Training Technique:</strong></p><p>Since google colab works only for 12 hours without session timeout, and it is impossible to train BERT model for 4 epochs together, a simple trick was done to make it happen.<br>The BERT py torch model is trained for 5L training data and validated with 10K validation data for just one epoch.<br>After which it is saved as file and then a new google colab session is started and again the previously trained model is trained with 5L data for another epoch.</p><p>By following this approach, we train the BERT model for 4 epoch by storing and training the BERT model of previous epoch</p><pre>param_optimizer = list(model.named_parameters())<br>no_decay = [&#39;bias&#39;, &#39;gamma&#39;, &#39;beta&#39;]<br>optimizer_grouped_parameters = [<br>    {&#39;params&#39;: [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)],<br>     &#39;weight_decay_rate&#39;: 0.01},<br>    {&#39;params&#39;: [p for n, p in param_optimizer if any(nd in n for nd in no_decay)],<br>     &#39;weight_decay_rate&#39;: 0.0}<br>]</pre><pre>optimizer = BertAdam(optimizer_grouped_parameters,<br>                     lr=2e-5,<br>                     warmup=.1)</pre><p>Training the BERT model</p><pre># Store our loss and accuracy for plotting<br>train_loss_set = []</pre><pre># Number of training epochs (authors recommend between 2 and 4)<br>epochs = 4</pre><pre># trange is a tqdm wrapper around the normal python range<br>for _ in trange(epochs, desc=&quot;Epoch&quot;):<br>  <br>  <br>  # Training<br>  <br>  # Set our model to training mode (as opposed to evaluation mode)<br>  model.train()<br>  <br>  # Tracking variables<br>  tr_loss, tr_accuracy, tr_f1_score = 0, 0, 0<br>  nb_tr_examples, nb_tr_steps = 0, 0</pre><pre># Train the data for one epoch<br>  for step, batch in enumerate(train_dataloader):<br>    if nb_tr_steps%1000 == 0:<br>      print(&quot;Step&quot;, nb_tr_steps)<br>    # Add batch to GPU<br>    batch = tuple(t.to(device) for t in batch)<br>    # Unpack the inputs from our dataloader<br>    b_input_ids, b_input_mask, b_labels = batch<br>    # Clear out the gradients (by default they accumulate)<br>    optimizer.zero_grad()<br>    # Forward pass<br>    loss = model(b_input_ids, token_type_ids=None, attention_mask=b_input_mask, labels=b_labels)<br>    train_loss_set.append(loss.item())    <br>    # Backward pass<br>    loss.backward()<br>    # Update parameters and take a step using the computed gradient<br>    optimizer.step()<br>    <br>    with torch.no_grad():<br>      # Forward pass, calculate logit predictions<br>      logits = model(b_input_ids, token_type_ids=None, attention_mask=b_input_mask)<br>    <br>    # Move logits and labels to CPU<br>    #print(&quot;logits&quot;, logits)<br>    logits = logits.detach().cpu().numpy()<br>    label_ids = b_labels.to(&#39;cpu&#39;).numpy()</pre><pre>tmp_tr_accuracy = flat_accuracy(logits, label_ids)<br>    tmp_f1_score = f1(label_ids, logits)<br>    <br>    tr_accuracy += tmp_tr_accuracy<br>    tr_f1_score += tmp_f1_score<br>    <br>    # Update tracking variables<br>    tr_loss += loss.item()<br>    nb_tr_examples += b_input_ids.size(0)<br>    nb_tr_steps += 1</pre><pre>  print(&quot;Train loss: {}&quot;.format(tr_loss/nb_tr_steps))<br>  print(&quot;Train Accuracy: {}&quot;.format(tr_accuracy/nb_tr_steps))<br>  print(&quot;Train f1-score: {}&quot;.format(tr_f1_score/nb_tr_steps))<br>    <br>    <br># Validation<br># Put model in evaluation mode to evaluate loss on the validation set<br>  model.eval()</pre><pre># Tracking variables <br>  eval_loss, eval_accuracy, eval_f1_score = 0, 0, 0<br>  nb_eval_steps, nb_eval_examples = 0, 0</pre><pre># Evaluate data for one epoch<br>  for batch in validation_dataloader:<br>    # Add batch to GPU<br>    batch = tuple(t.to(device) for t in batch)<br>    # Unpack the inputs from our dataloader<br>    b_input_ids, b_input_mask, b_labels = batch<br>    # Telling the model not to compute or store gradients, saving memory and speeding up validation<br>    with torch.no_grad():<br>      # Forward pass, calculate logit predictions<br>      logits = model(b_input_ids, token_type_ids=None, attention_mask=b_input_mask)<br>    <br>    # Move logits and labels to CPU<br>    logits = logits.detach().cpu().numpy()<br>    label_ids = b_labels.to(&#39;cpu&#39;).numpy()</pre><pre>tmp_eval_accuracy = flat_accuracy(logits, label_ids)<br>    tmp_f1_score = f1(label_ids, logits)<br>    <br>    eval_accuracy += tmp_eval_accuracy<br>    eval_f1_score += tmp_f1_score<br>    nb_eval_steps += 1</pre><pre>print(&quot;Validation Accuracy: {}&quot;.format(eval_accuracy/nb_eval_steps))<br>  print(&quot;Validation f1-score: {}&quot;.format(eval_f1_score/nb_eval_steps))</pre><h4>4) Results</h4><p>The result was actually magical. Other than typically simple neural networks which I trained and which was a completely dumb model, BERT worked like a charm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VrP3GzlICLezrjUONDyG8g.png" /><figcaption>Confusion matrix, precision and recall matrix for BERT Model</figcaption></figure><p>The BERT model gives a very good predictions for class 1.The class 0 has a very good recall value of 0.93 while that of the class 1 gives a comparatively lower recall value 0.644.The F1-Score obtained is 0.9472 and the accuracy of 0.89 indicates that the model performed pretty well.</p><p>Another notable point is that the MRR is very good, an MRR of 0.0.8862530 is achieved by this BERT model which shows that even though it some of the correct answers are not predicted correctly they are on a higher rank when compared to their co-wrong answers data points.</p><p>But the results will improve well if we train the BERT for much large dataset and to a bit high number of epochs.Due to the memory and session timeout constraints of the BERT model, it was very difficult to train the model for higher epoch with larger amount of data.But with higher computational and memory power, the result could be improved.</p><p>The above case study was a nice example to show that for solving an deep learning problem when we don’t have sufficient infrastructure and computational resource, transfer learning is the best technique that works like a charm :)</p><h3>References:</h3><ol><li><a href="https://towardsdatascience.com/bert-explained-state-of-the-art-language-model-for-nlp-f8b21a9b6270">https://towardsdatascience.com/bert-explained-state-of-the-art-language-model-for-nlp-f8b21a9b6270</a></li><li><a href="https://mccormickml.com/2019/07/22/BERT-fine-tuning/">https://mccormickml.com/2019/07/22/BERT-fine-tuning/</a></li></ol><p>My git hub link to the entire work: <a href="https://github.com/gayathriabhi/BERT-model-to-predict-the-correct-descriptive-answer">https://github.com/gayathriabhi/BERT-model-to-predict-the-correct-descriptive-answer</a></p><p>LinkedIn Profile: <a href="https://www.linkedin.com/in/gayathri-s-a90322126/">https://www.linkedin.com/in/gayathri-s-a90322126/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2c4d94e6098" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/use-transfer-learning-in-bert-model-to-predict-correct-descriptive-answer-for-open-ended-questions-e2c4d94e6098">Use Transfer learning in BERT model to predict correct descriptive answer for open-ended 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>
        <item>
            <title><![CDATA[Building a simple Stack overflow search engine to predict posts related to given query post]]></title>
            <link>https://medium.com/analytics-vidhya/building-a-simple-stack-overflow-search-engine-to-predict-posts-related-to-given-query-post-56b3e508520c?source=rss-439ba5e2de57------2</link>
            <guid isPermaLink="false">https://medium.com/p/56b3e508520c</guid>
            <category><![CDATA[search-engines]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Gayathri s]]></dc:creator>
            <pubDate>Sat, 19 Oct 2019 17:31:29 GMT</pubDate>
            <atom:updated>2019-11-22T08:58:35.455Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a simple Stack overflow search engine to predict semantically similar posts related to given query post using machine learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yg2DHASe7om_TsIz0E5UuA.png" /></figure><p><em>Stack Overflow — is a obvious life saver for many of the developers who use it in a day-to-day basis( saying this as I myself is a developer :) ). It is a question and answer site for professional and enthusiast programmers. It features questions and answers on a wide range of topics in computer programming and also now it is not limited to computer programming alone but answers questions across a wide range of spectrum</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kSn8NGOpRpfiT5O0VlrEJA.png" /><figcaption>A typical stackoverflow question answer page</figcaption></figure><p><em>This is a quick introduction on what is stackoverflow before dive deep into the project</em></p><h3><strong><em>About the project</em></strong></h3><p>Stack overflow website also has this particular sections in their all their question and answers page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*2Sr9gg2gkpGJKB1lRGWSuQ.png" /><figcaption>Posts very much related to the post in current page</figcaption></figure><p>It lists out all the questions which are related to the current questions which could help the user to navigate through the current page itself to find the suitable questions page if the current page doesn’t cater to their needs. The project aims to predict this related posts for a given query post like in the image for the question: load data txt from pandas, it predicts similar posts as shown in the picture above.</p><p>Since we are building this as a search engine in addition to the semantic relevance of the predicted posts with respect to the query post, there are additional constraints to be satisfied</p><ol><li>Low latency — prediction time should be less</li><li>Scalability — must work even when the volume of data we are searching for increases tremendously</li></ol><p>The whole problem is to build a search engine based on StackOverflow questions, the search results should include the semantic meaning, with scalable architecture that return results in very less time.</p><h3>Approach</h3><h4><strong>1. Data Collection</strong></h4><p>Data Link: <a href="https://meta.stackexchange.com/questions/138356/how-do-i-download-stack-overflows-data">https://meta.stackexchange.com/questions/138356/how-do-i-download-stack-overflows-data</a></p><p>The above link contains all stack overflow data in various topics among which only the these posts files are downloaded.</p><pre><a href="https://archive.org/download/stackexchange/cs.meta.stackexchange.com.7z">cs.meta.stackexchange.com.7z</a><br><a href="https://archive.org/download/stackexchange/cs.stackexchange.com.7z">cs.stackexchange.com.7z</a><br><a href="https://archive.org/download/stackexchange/datascience.meta.stackexchange.com.7z">datascience.meta.stackexchange.com.7z</a><br><a href="https://archive.org/download/stackexchange/datascience.stackexchange.com.7z">datascience.stackexchange.com.7z</a><br><a href="https://archive.org/download/stackexchange/ai.meta.stackexchange.com.7z">ai.meta.stackexchange.com.7z</a><br><a href="https://archive.org/download/stackexchange/ai.stackexchange.com.7z">ai.stackexchange.com.7z</a><br><a href="https://archive.org/download/stackexchange/computergraphics.meta.stackexchange.com.7z">computergraphics.meta.stackexchange.com.7z</a><br><a href="https://archive.org/download/stackexchange/computergraphics.stackexchange.com.7z">computergraphics.stackexchange.com.7z</a></pre><p>The downloaded zip files has questions and answer regarding four major topics — computer science, data science, AI and computer graphics. The above files when uncompressed gives a lots of files among which only the posts.xml files in each of the uncompressed directory is obtained since only that particular file contains the post text.</p><p>Each post.xml file is named in accordance to their topic and stored in the XML Files directory</p><pre>XML Files<br>  -&gt; DataScienceMeta_Posts.xml<br>  -&gt; ComputerGraphicsMeta_Posts.xml<br>  -&gt; AI_Posts.xml<br>  -&gt; CSMeta_Posts.xml<br>  -&gt; AIMeta_Posts.xml<br>  -&gt; CS_Posts.xml<br>  -&gt; ComputerGraphics_Posts.xml<br>  -&gt; DataScience_Posts.xml</pre><h4>2. <strong>Data Preprocessing</strong></h4><p>The obtained 9 xml files contains lot more data like postId, comments, upvotes etc in addition to the text data in the xml format. Hence it is necessary to parse the xml file and obtain only the post text attribute of each of the xml element present in the files</p><pre># specifying the fields for csv file <br>fields = [&#39;Id&#39;, &#39;Text&#39;, &#39;Topic&#39;]</pre><pre>def parseXML(xmlfile, start_count): <br>    #create element tree object <br>    print(&quot;File&quot;, xmlfile)<br>    tree = ET.parse(xmlfile) <br>    topic = xmlfile.split(&quot;/&quot;)[1].split(&quot;_&quot;)[0]<br>    # get root element <br>    root = tree.getroot() <br>    # create empty list for news items <br>    newsitems = [] <br>    count = start_count<br>    # iterate news items <br>    for each_row in root.iter(&quot;row&quot;):<br>        news = {}<br>        news[&quot;Id&quot;] = count<br>        news[&quot;Text&quot;] = each_row.attrib[&quot;Body&quot;]<br>        news[&quot;Topic&quot;] = topic <br>        count=count+1<br>        newsitems.append(news)<br>    # return news items list <br>    print(&quot;len&quot;, len(newsitems))<br>    return newsitems</pre><p>Each of the xml file is parsed to obtain the text and corresponding topic of the post which is the file name of the xml file and stored along with a generated id field</p><pre>def savetoCSV(newsitems, filename): <br>    # writing to csv file <br>    with open(filename, &#39;w&#39;) as csvfile: <br>        # creating a csv dict writer object <br>        writer = csv.DictWriter(csvfile, fieldnames = fields) <br>        # writing headers (field names) <br>        writer.writeheader() <br>        # writing data rows <br>        writer.writerows(newsitems)</pre><p>The result obtained is stored in a same name as a CSV file in a directory named CSV Files</p><pre># specifying the fields for csv file <br>fields = [&#39;Id&#39;, &#39;Text&#39;, &#39;Topic&#39;]  <br>start_count = 0<br>for each_file in postfiles:<br>    print(each_file)<br>    # parse xml file <br>    newsitems = parseXML(&quot;XML Files/&quot;+each_file, start_count) <br>    csv_filename = each_file.split(&#39;.&#39;)[0] + &quot;.csv&quot;<br>    print(&quot;csv_filename&quot;, csv_filename)<br>    # store news items in a csv file <br>    savetoCSV(newsitems, &quot;CSV Files/&quot; + csv_filename)<br>    start_count = len(newsitems) + start_count</pre><p>The CSV Files directory looks like</p><pre>CSV Files<br>  -&gt; DataScienceMeta_Posts.csv<br>  -&gt; ComputerGraphicsMeta_Posts.csv<br>  -&gt; AI_Posts.csv<br>  -&gt; CSMeta_Posts.csv<br>  -&gt; AIMeta_Posts.csv<br>  -&gt; CS_Posts.csv<br>  -&gt; ComputerGraphics_Posts.csv<br>  -&gt; DataScience_Posts.csv</pre><p>All of the files in the CSV Files are then parsed to data frames which is then merged together and saved in a pickle file which is the final data file which we will be using for further processing.The structure of our final pickle file is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*lBlpFH5B4vQ3Fchsy-Yung.png" /></figure><h4>3. Data Cleaning</h4><p>Since the text obtained is from a website, it typically tend to have a lot of html entities and hence must be subjected to extensive data preprocessing step</p><p>The various data preprocessing treatment done are:</p><ol><li>Removal of HTML tags</li><li>Removal of URLs</li><li>Removal of Punctuations ( #,&amp;,*) and stop words etc</li></ol><p>Another key and different data preprocessing step done is:</p><p>4) Removal of programming code</p><p>for(i=0;i&lt;n;i++) { print(i) }</p><p>Since this is a majorly computer science programming question and answer portal most of the questions and answer posts tend to have programming code which has a lot of punctuation and unique structure which would lose meaning once subjected to data preprocessing.</p><p>Hence programming code should be removed and then feature engineered separately to obtain a good prediction.</p><h4>3. <strong>Feature Engineering</strong></h4><p>Feature Engineering is one of the most important and crucial step of solving any data science problem.A good Feature engineering done could help the model a lot in the prediction.Here I have come up with three new features.</p><ol><li>topic</li><li>programming code</li><li>Does cites the same link</li></ol><h4><strong>3a) topic</strong></h4><p>The topic of each of the posts is used as one of the feature as posts with similar topic tends to more similar than the others.The topic feature is one hot encoded as it is a categorical feature.</p><h4>3b) Programming code</h4><p>Though the programming code in each of the posts is removed, it is provides very important information which must not be lost.Hence the programming code is feature engineered separately so that we could extract more information for it. It is done by removing the code portion separately from each of the post and vectorizing it and clustering the code vectors by k-means clusters. By this way, we could obtain beautiful insights about the programming code as shown in the images below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*103900ps6s1MwpsTQQeXYg.png" /><figcaption>database code cluster</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*nJVZp8tuQwRPaVADS5ZSvQ.png" /><figcaption>tensorflow code cluster</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*FzNEQAP4YqaT_cP3zmyGgQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*1RQBt5Humay7yobPgm1_MA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*3ETqhhk8MxalG3Wqa_wD8g.png" /><figcaption>python dataframe code cluster</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*BfIIMZDONbpB_MDt1coSDw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*rAhGT_WuU03M0YLkjpYnOw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*5DnMQjD2zcHGsWsF1SXPPQ.png" /><figcaption>java code cluster</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*TpZqqtL-zHHT2opBIYbkEQ.png" /><figcaption>Knn code cluster</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*Xgi1g64Xu86_0-_3qhe9Ig.png" /><figcaption>numpy functions code cluster</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*38h8NMdR3Y3_JZmmna_JiA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*fvG0zN-Ic_S67-Byw7WvIA.png" /><figcaption>sklearn model train and test code cluster</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*FMTZy9AcMMgLuRLlgyt7jw.png" /><figcaption>LSTM code cluster</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*qp-TN86QUU2VCSqEAsbg6A.png" /><figcaption>Deep learning keras code cluster</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*Thq-wgyesMbyyYzqaroZmw.png" /><figcaption>Float data code cluster</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*hmYvZ3X8StXrak5JF8dqXQ.png" /><figcaption>regular expression code cluster</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*54rC-M8X0iVPCuCkimR5OQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*F10VkwmIjjarZXbrLlSOtw.png" /><figcaption>c++ input output code cluster</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*oBf5t9hwxjmQ69BzM4O5_A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*EsjGXL9mfgUvWkeqkfXPJQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*uJbXaCUqB8IHtxxImOWWJQ.png" /><figcaption>python class code cluster</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*dwrL9HdeaItX6Ddb8qEYXQ.png" /><figcaption>Data structure code cluster</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*oJWJk60qptKSfsOOfEBLtg.png" /><figcaption>double datatype code cluster</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*FcKt8lkLNIrgYQOX2WOhqA.png" /><figcaption>python data structures clusters</figcaption></figure><p>As we could see, the code is clustered into relevant type. A total of 24 clusters is obtained and the post without code is put into a separate 25th cluster. Thus code cluster is now a categorical feature for similar post prediction which is also one hot encoded</p><h4>3c) Does_site_the_same_url</h4><p>Similar to programming code, URL is also one such feature that require special featurization. Since URL too has a special structure, normal data processing treatment will make it loose its meaning. URLs can be feature engineered separately by finding if two posts cites the same url or not, if so then may be both refers to the similar thing.</p><p>On analysis, we could find that nearly 31% of the urls cited are repeated ones. Hence there is a descent probability that cites will be repeat and that can be used to find similar posts</p><h4>3d) Document Embeddings</h4><p>For vectorization of the preprocessed post text data, Five types of embeddings is used</p><ol><li>Glove Vectors embedding</li><li>TF-IDF Weighted Glove vectors embedding</li></ol><p>Along with these, anew technique called Yet another Keyword Extractor is used to extract keyword from the posts text and then vectorizing it.</p><p>YAKE — Yet Another Keyword Extractor is one of the nice approaches for extracting keywords from the text. It has proved to outperform a number of unsupervised methods and a supervised method under a number of collections of different sizes, languages or domains.</p><p>To learn more about YAKE look into this page:<a href="https://github.com/LIAAD/yake">https://github.com/LIAAD/yake</a></p><p>Hence it is used to extract the keywords in each of the posts text first and then apply embeddings to it</p><p>3) YAKE based Keyword Extraction + Glove Vectors embedding</p><p>4) YAKE based Keyword Extraction + TF-IDF Weighted Glove vectors embedding</p><pre>def tokenization(keywords_text):<br>    tokenizer = RegexpTokenizer(r&#39;\w+&#39;)<br>    return tokenizer.tokenize(keywords_text)</pre><pre>#Converting each posts text into corresponding keyword sets<br>simple_kwextractor = yake.KeywordExtractor()<br>questions_keywords_text = []<br>for i in range(preprocessed_text.shape[0]):<br>    if i%10 == 0:<br>        print(i,&quot;vectors finished&quot;)<br>    keyword_simple = simple_kwextractor.extract_keywords(preprocessed_text[i])<br>    keyword_text = &quot;&quot;<br>    for each_kw in keyword_simple:<br>        keyword_text += each_kw[0] + &quot; &quot;<br>    questions_keywords_text.append(set(tokenization(keyword_text)))<br>questions_keywords_sets = np.array(questions_keywords_text)</pre><p>5) BERT Embedding</p><p>BERT model, which stands for Bidirectional Encoder Representations from Transformer published by the google is currently the state of the art model for doing NLP related tasks. BERT which is an LSTM model works based on the concept of attention trying to predict the next token based on the series of the previous tokens it encountered. BERT based embedding may prove useful for this project to extract more meaningful information from the post text.</p><pre>def avg_of_token_embedding(result):<br>  document_embeddings = np.zeros(768)<br>  count = 0<br>  for i in range(len(result)):<br>    for j in range(len(result[i][1])):<br>       document_embeddings = document_embeddings + result[i][1][j]<br>            count = count + 1<br>  return (document_embeddings/count)</pre><pre>from bert_embedding import BertEmbedding<br>bert_document_embeddings = []<br>for i in range(preprocesses_text.shape[0]):<br>    sentences = bert_abstract.split(&#39; &#39;)<br>    bert_embedding = BertEmbedding()<br>    token_embedding = bert_embedding(preprocesses_text[i],&#39;sum&#39;)<br>    bert_embedding_vector = avg_of_token_embedding(token_embedding)<br>    bert_document_embeddings.append(bert_embedding_vector)<br>bert_document_embeddings = np.array(bert_document_embeddings)</pre><h4>4. Building a simple search Engine</h4><p>This is the most crucial part of the solution as the search engine should be scalable and have less latency.Similarity between the two post text is calculated in the following way:</p><pre><strong>Post Similarity(i,j) = <br>cosine_similarity(post_vector(i),post_vector(j)) + similarity(topic_vector(i), topic_vectorr(j)) + similarity(code_cluster(i), code_cluster(j)) + <br>number of common urls</strong></pre><p>Based on the above formula, similarity between two post is computed.Cosine similarity is used for post text as euclidean distance is prone to curse of dimensionality problem for high dimensions. For topic vector and code cluster vector, the similarity is computed as inverse of euclidean distance</p><pre>               <strong><em>similarity = 1/ euclidean distance</em></strong></pre><p>To build a search engine, an efficient <strong>map-reduce like</strong> solution is implemented where 8 processes are spawn to run independently.</p><p>For a given query post, each processes processes 1/8th part of the total posts data returns an 10 length list which the top 10 highest similarity posts of the total posts which it computed . Then all the 10 length list returned by all the processes are combined together and sorted to get the total top 10 similarity.A simple map reduce like technique enabled the latency to be within 20 secs.</p><p>Code for the search engine:</p><pre>import multiprocessing<br>alpha = 0.001</pre><pre><strong>//returns topic wise similarity of two posts</strong><br>def get_topic_similarity(ind1, ind2):<br>    dist = euclidean_distances(topics[ind1], topics[ind2])[0][0]<br>    if dist == 0:<br>        return 1/(dist+alpha)<br>    else:<br>        return dist</pre><pre><strong>//returns code wise similarity of two posts</strong><br>def get_code_similarity(ind1, ind2):<br>    dist = euclidean_distances(code_cluster_list[ind1].reshape(-1,1), <br>                   code_cluster_list[ind2].reshape(-1, 1))[0][0]<br>    if dist == 0:<br>        return 1/(dist+alpha)<br>    return dist<br>      </pre><pre>def insert_into_top_k_similar_docs(top_k_similar_docs,<br>vec_similarity, doc_id):<br>    doc_dict = dict()<br>    doc_dict[&quot;doc_id&quot;] = doc_id<br>    doc_dict[&quot;similarity&quot;] = vec_similarity<br>    should_insert = False<br>    for i in range(11):<br>        if i == 10:<br>            return<br>        if vec_similarity &gt; top_k_similar_docs[i][&#39;similarity&#39;]:<br>            should_insert = True<br>            break<br>   <br>    if should_insert:<br>        docs_place = i<br>        temp_list = []<br>        for i in range(docs_place, k-1):<br>            #print(&quot;it 2&quot;, i)<br>            temp_list.append(top_k_similar_docs[i])<br>        ind = 0<br>        for i in range(docs_place+1 , k):<br>            top_k_similar_docs[i] = temp_list[ind]<br>            ind = ind + 1<br>        top_k_similar_docs[docs_place] = doc_dict</pre><pre><strong>// Finds the top 10 similar posts for a given query post from the <br>// posts in the start and end range   </strong>    <br>def find_vector_similarity(preprocessed_text_vector, test_query_point, start, end, topic_weight=1, code_weight=1,<br>                          cites_weight=1):<br>    top_k_similar_docs = []<br>    for i in range(10):<br>        doc_dict = dict()<br>        doc_dict[&#39;doc_id&#39;] = 0<br>        doc_dict[&#39;similarity&#39;] = -1<br>        top_k_similar_docs.append(doc_dict)<br>      <br>    for i in range(start, end):<br>        if i &gt;= preprocessed_text_vector.shape[0]:<br>            return<br>        vec_similarity = cosine_similarity(preprocessed_text_vector[i].reshape(1,-1), <br>                                    preprocessed_text_vector[test_query_point].reshape(1,-1))[0][0]<br>        topicwise_similarity = get_topic_similarity(i, test_query_point)* topic_weight<br>        codewise_similarity = get_code_similarity(i, test_query_point) * code_weight<br>        cites_similarity = get_cites_similarity(i, test_query_point)<br>        if cites_similarity:<br>            cites_similarity = cites_similarity * cites_weight<br>            vec_similarity = vec_similarity + topicwise_similarity + codewise_similarity + cites_similarity<br>        else:<br>            vec_similarity = vec_similarity + topicwise_similarity + codewise_similarity<br>        vec_sim_list.append(vec_similarity)<br>        insert_into_top_k_similar_docs(top_k_similar_docs, vec_similarity, i)  <br>    return top_k_similar_docs</pre><pre>def simple_search_engine(preprocessed_text_vector, test_sample, topic_weight=1, code_weight=1, cites_weight=1):<br>    count = 0<br>    posts_text = pd.read_pickle(&#39;Preprocessed_questions_text.pkl&#39;)[&#39;Text&#39;].values<br>    for each_test_point in test_sample:<br>        list_of_top_k_docs = [] <br>        start_time = datetime.now()<br>        #print(each_test_point)<br>        #print(&quot;top_k_similar_docs&quot;, top_k_similar_docs)<br>        vec_sim_list = []<br>        test_query_point = preprocessed_text_vector[each_test_point]<br>        print(&quot;Query posts&quot;,each_test_point, &quot;:&quot; , posts_text[each_test_point])<br>        print(&quot;#&quot;*100)<br>        start = 0<br>        step = preprocessed_text_vector.shape[0]/8<br>        input_list = []<br>        while start &lt; preprocessed_text_vector.shape[0]:      <br>            input_list.append([preprocessed_text_vector, each_test_point, start, start+step, <br>                               topic_weight, code_weight, cites_weight ])<br>            start = start+step<br>        pool = multiprocessing.Pool(processes=4)<br>        tasks=[]<br>        for each in input_list:<br>            tasks.append(pool.apply_async(find_vector_similarity,each))<br>        pool.close()<br>        pool.join()<br>        for each in tasks:<br>            each.wait()<br>            result = each.get()<br>            list_of_top_k_docs.extend(result)<br>        quickSort(list_of_top_k_docs, 0, len(list_of_top_k_docs))<br>        list_of_top_k_docs = list_of_top_k_docs[0:10]<br>        total_time = (datetime.now() - start_time).total_seconds()<br>        print(&quot;Total time taken:&quot;, humanize_seconds(total_time))<br>        print(&quot;The Most similar &quot;,k,&quot;posts are:&quot;)<br>        for each in list_of_top_k_docs:<br>            print(posts_text[each[&#39;doc_id&#39;]])<br>            print(&quot;#&quot;*100)<br>        print(&quot;*&quot;*200)</pre><h4>5. Comparing performance of five embedding techniques</h4><p>We don’t have explicit performance metric to evaluate of quality of the predictions we made, we have to evaluate the predictions made by manually reading the 10 post predicted by the model.Based on that, the performance of five embedding which we used is:</p><ol><li>In similar posts prediction using glove vectors and TF-IDF weighted glove vectors,The first posts is on an NP complete problem called hamiltonian cycle. We could observe on using the glove and TF-IDF weighted glove vectors, it predicts posts related to the theory of computation, time complexity and some NP completeness posts etc.</li></ol><p>An Example prediction by simple glove vectors:</p><pre><strong>Query Posts:<br></strong>Hint: Hamiltonian Cycle is $NP$-Complete.</pre><pre><strong>Sample predicted posts:</strong></pre><pre>1) &lt;p&gt;Hint: This is just the well-known NP-complete problem PARTITION.&lt;/p&gt;</pre><pre>2) &lt;p&gt;Is there a notion of a context-free complete language (in the analogous sense to a &lt;span class=&quot;math-container&quot;&gt;$NP$&lt;/span&gt;-complete language)?&lt;/p&gt;</pre><pre>3) &lt;p&gt;For example;&lt;/p&gt;<br>&lt;p&gt;Is {0,1,{a,b,c},d,e} a valid alphabet to form a language over and is it usable in any context?&lt;/p&gt;</pre><pre>4) &lt;p&gt;How Decision procedure and Decidable problem are different from each other?<br>Both are having solutions in yes and no form. Is any else solution for both?  &lt;/p&gt;</pre><p>Example predictions by TF-IDF weighted glove vectors:</p><pre><strong>Query Posts:<br></strong>Hint: Hamiltonian Cycle is $NP$-Complete.</pre><pre><strong>Sample predicted posts:</strong></pre><pre>1) &lt;p&gt;Hint: This is just the well-known NP-complete problem PARTITION.&lt;/p&gt;</pre><pre>2) &lt;p&gt;Is there a notion of a context-free complete language (in the analogous sense to a &lt;span class=&quot;math-container&quot;&gt;$NP$&lt;/span&gt;-complete language)?&lt;/p&gt;</pre><pre>3) &lt;p&gt;Can an ambiguous context-free grammar be converted into Chomsky normal form? I think the answer is yes.&lt;/p&gt;</pre><pre>4) &lt;p&gt;Time complexity, like any other nontrivial property of programs, is undecidable: there can be no algorithm to compute it, in Python or anything else.&lt;/p&gt;</pre><p>2) Predictions based on keywords extracted Glove vectors seems to be little bit more refined than the predictions done using the glove vectors.</p><p>Example predictions by keyword extracted glove vectors:</p><pre><strong>Query Posts:<br></strong>Hint: Hamiltonian Cycle is $NP$-Complete.</pre><pre><strong>Sample predicted posts:</strong></pre><pre>1) &lt;p&gt;Is there a notion of a context-free complete language (in the analogous sense to a &lt;span class=&quot;math-container&quot;&gt;$NP$&lt;/span&gt;-complete language)?&lt;/p&gt;</pre><pre>2) &lt;p&gt;Does it exist an algorithm to find a median of table with a complexity nlog(n) Thank&lt;/p&gt;</pre><pre>3) &lt;p&gt;2^n=O(3^n) : This is true or it is false if n&gt;=0 or if n&gt;=1<br>since 2^n may or not be element of O(3^n)<br>I need a hint to figure the problem&lt;/p&gt;</pre><pre>4) &lt;p&gt;Yes and yes. Look at this graph:&lt;/p&gt;<br><br>&lt;ul&gt;<br>&lt;li&gt;$V=\{1,2,3,4\}$&lt;/li&gt;<br>&lt;li&gt;$E=\{\{1,2\},\{2,3\},\{3,4\},\{4,1\}\}$&lt;/li&gt;<br>&lt;/ul&gt;<br><br>&lt;p&gt;There is neither articulation point nor bridge. But if you delete any node/edge...&lt;/p&gt;</pre><p>Example predictions by keyword extracted TF-IDF glove vectors:</p><pre><strong>Query Posts:<br></strong>Hint: Hamiltonian Cycle is $NP$-Complete.</pre><pre><strong>Sample predicted posts:</strong></pre><pre>1) &lt;p&gt;Is there a notion of a context-free complete language (in the analogous sense to a &lt;span class=&quot;math-container&quot;&gt;$NP$&lt;/span&gt;-complete language)?&lt;/p&gt;<br><br>2) &lt;p&gt;Does it exist an algorithm to find a median of table with a complexity nlog(n) <br>Thank&lt;/p&gt;<br><br>3) &lt;p&gt;2^n=O(3^n) : This is true or it is false if n&gt;=0 or if n&gt;=1<br>since 2^n may or not be element of O(3^n)<br>I need a hint to figure the problem&lt;/p&gt;<br><br>4) &lt;p&gt;Yes and yes. Look at this graph:&lt;/p&gt;<br><br>&lt;ul&gt;<br>&lt;li&gt;$V=\{1,2,3,4\}$&lt;/li&gt;<br>&lt;li&gt;$E=\{\{1,2\},\{2,3\},\{3,4\},\{4,1\}\}$&lt;/li&gt;<br>&lt;/ul&gt;<br><br>&lt;p&gt;There is neither articulation point nor bridge. But if you delete any node/edge...&lt;/p&gt;</pre><p>3) Predictions based on the BERT embedding seems to be very much more refined than the keyword extracted glove and keyword extracted tf-idf weighted glove vectors, since the post is on NP-complete problem, more posts on NP complete problems are predicted than any other. Also for the second svm posts it predicts more posts on the SVM than any other topics</p><p>An Example prediction by BERT Embeddings:</p><pre><strong>Query Posts:<br></strong>Hint: Hamiltonian Cycle is $NP$-Complete.</pre><pre><strong>Sample predicted posts:</strong></pre><pre>1) &lt;p&gt;Yes, this is decidable, because you can do an exhaustive search of all possible paths. There is no need to look at any paths that repeat a vertex, since the &quot;detour&quot; could be skipped. But the length of any non-repetitive path is bounded by the size of the graph, which is finite, and so there are only finitely many such paths, which can be checked one by one.&lt;/p&gt;<br><br>&lt;p&gt;What is not decidable is the following: given an infinite graph $G$ and two vertices $a$ and $b$, decide whether there is a path from $a$ to $b$. This is not decidable if the graph is given as an oracle and is also not decidable if the graph is given via a program that computes it. &lt;/p&gt;</pre><pre>2) &lt;blockquote&gt;<br>  &lt;p&gt;What is the time complexity of finding the diameter of a graph<br>  $G=(V,E)$?&lt;/p&gt;<br>  <br>  &lt;ul&gt;<br>  &lt;li&gt;${O}(|V|^2)$&lt;/li&gt;<br>  &lt;li&gt;${O}(|V|^2+|V| \cdot |E|)$&lt;/li&gt;<br>  &lt;li&gt;${O}(|V|^2\cdot |E|)$&lt;/li&gt;<br>  &lt;li&gt;${O}(|V|\cdot |E|^2)$&lt;/li&gt;<br>  &lt;/ul&gt;<br>&lt;/blockquote&gt;<br><br>&lt;p&gt;The diameter of a graph $G$ is the maximum of the set of shortest path distances between all pairs of vertices in a graph.&lt;/p&gt;<br><br>&lt;p&gt;I have no idea what to do about it, I need a complete analysis on how to solve a problem like this.&lt;/p&gt;</pre><pre>3) &lt;p&gt;When searching graphs, there are two easy algorithms: &lt;strong&gt;breadth-first&lt;/strong&gt; and &lt;strong&gt;depth-first&lt;/strong&gt; (Usually done by adding all adjactent graph nodes to a queue (breadth-first) or stack (depth-first)).&lt;/p&gt;<br><br>&lt;p&gt;Now, are there any advantages of one over another?&lt;/p&gt;<br><br>&lt;p&gt;The ones I could think of:&lt;/p&gt;<br><br>&lt;ul&gt;<br>&lt;li&gt;If you expect your data to be pretty far down inside the graph, &lt;em&gt;depth-first&lt;/em&gt; might find it earlier, as you are going down into the deeper parts of the graph very fast.&lt;/li&gt;<br>&lt;li&gt;Conversely, if you expect your data to be pretty far up in the graph, &lt;em&gt;breadth-first&lt;/em&gt; might give the result earlier.&lt;/li&gt;<br>&lt;/ul&gt;<br><br>&lt;p&gt;Is there anything I have missed or does it mostly come down to personal preference?&lt;/p&gt;</pre><pre>4) &lt;p&gt;Breadth-first and depth-first certainly have the same worst-case behaviour (the desired node is the last one found). I suspect this is also true for averave-case if you don&#39;t have information about your graphs.&lt;/p&gt;<br><br>&lt;p&gt;One nice bonus of breadth-first search is that it finds shortest paths (in the sense of fewest edges) which may or may not be of interest.&lt;/p&gt;<br><br>&lt;p&gt;If your average node rank (number of neighbours) is high relative to the number of nodes (i.e. the graph is dense), breadth-first will have huge queues while depth-first will have small stacks. In sparse graphs, the situation is reversed. Therefore, if memory is a limiting factor the shape of the graph at hand may have to inform your choice of search strategy.&lt;/p&gt;</pre><p>4) Thus predictions based on BERT embeddings seems to be more refined than the predictions based on keyword extracted text embeddings which in turns performs better than the normal glove vectors embeddings. We could also observe TF-IDF weighted glove vectors does almost the same job in terms of the prediction. Hence, TF-IDF values doesn’t add any impact to improve the prediction performance</p><h4>5. Reference</h4><ol><li>YAKE — Yet another keyword extractor <a href="https://github.com/LIAAD/yake">https://github.com/LIAAD/yake</a></li><li>Bert embeddings — <a href="https://github.com/imgarylai/bert-embedding">https://github.com/imgarylai/bert-embedding</a></li></ol><p>To view the entire work, please visit my git hub link:<a href="https://github.com/gayathriabhi/StackOverflow-Search-Engine">https://github.com/gayathriabhi/StackOverflow-Search-Engine</a></p><p>My LinkedIn profile: <a href="https://www.linkedin.com/in/gayathri-s-a90322126/">https://www.linkedin.com/in/gayathri-s-a90322126/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56b3e508520c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/building-a-simple-stack-overflow-search-engine-to-predict-posts-related-to-given-query-post-56b3e508520c">Building a simple Stack overflow search engine to predict posts related to given query post</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>