<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://nish-19.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="https://nish-19.github.io/" rel="alternate" type="text/html" /><updated>2026-01-19T12:54:13-08:00</updated><id>https://nish-19.github.io/feed.xml</id><title type="html">Nischal Ashok Kumar</title><subtitle>Personal Blog</subtitle><author><name>Nischal Ashok Kumar</name></author><entry><title type="html">Stable Baselines 3 Tutorial (Computerized Adaptive Testing)</title><link href="https://nish-19.github.io/posts/2023/12/blog-post-6/" rel="alternate" type="text/html" title="Stable Baselines 3 Tutorial (Computerized Adaptive Testing)" /><published>2023-12-26T00:00:00-08:00</published><updated>2023-12-26T00:00:00-08:00</updated><id>https://nish-19.github.io/posts/2023/12/blog-post-6</id><content type="html" xml:base="https://nish-19.github.io/posts/2023/12/blog-post-6/"><![CDATA[<p><img src="https://github.com/Nish-19/SB3-tutorial/assets/41947720/cc050964-5e21-43a2-8a14-a13654b68d6d" alt="pic" /></p>

<figcaption style="text-align: center;">Figure 1: Figure showing the MDP</figcaption>

<p>The goal of this blog is to present a tutorial on <a href="https://stable-baselines3.readthedocs.io/en/master/">Stable Baselines 3</a>, a popular Reinforcement Learning library with focus on implementing a custom environment and a custom policy. We will first describe our problem statement, discuss the MDP (Markov Decision Process), discuss the algorithms - <a href="https://openai.com/research/openai-baselines-ppo">PPO</a>, custom feature extractor PPO and custom policy (lstm bilinear policy with PPO).</p>

<h2 id="problem-statement">Problem Statement</h2>

<p>In the realm of computer science education, evaluating coding homework poses unique challenges that traditional methods struggle to address. Auto-grading systems, which automatically assess correctness and functionality using test cases, offer a valuable solution. However, as the complexity of coding assignments grows, the sheer volume of test cases can hamper system efficiency. Inspired by Computerized Adaptive Testing (CAT), which optimizes assessments based on prior responses, we aim to develop a policy that selects a minimal yet effective set of test cases, ensuring swift and accurate evaluations for both students and instructors.</p>

<h2 id="related-work">Related Work</h2>

<p>In Computerized Adaptive Testing (CAT), there are four essential components:</p>

<ol>
  <li><strong>Knowledge Level Estimator:</strong> Assesses the student’s current knowledge based on their responses to previously selected items.</li>
  <li><strong>Response Model:</strong> Estimates the likelihood of a student answering a specific item correctly using the current knowledge level and item features.</li>
  <li><strong>Pool of Available Items:</strong> A collection of test items from which the adaptive system selects questions.</li>
  <li><strong>Item Selection Algorithm:</strong> Chooses the next most informative item based on the response model output.</li>
</ol>

<p>The widely used Item-Response-Theory (IRT) model, specifically the simplest form (1PL), is often employed. In its basic form, the 1PL model is defined as:</p>

\[P(Y_{i, j} = 1) = \sigma(\theta_j - b_i)\]

<p>Here, \(\theta_j\) represents the student’s knowledge level, and \(b_i\)  is the difficulty of item \(i\).</p>

<h2 id="mdp-formulation">MDP Formulation</h2>

<h3 id="notation">Notation</h3>
<p>We denote the programming question statement as <strong>q</strong>; the solution (correct) code to the question as <strong>a</strong>; student <em>j</em>’s code as <strong>c<sub>j</sub></strong>; student <em>j</em>’s ground truth code quality (knowledge level) as <strong>θ<sub>j</sub></strong>; student <em>j</em>’s current code quality estimate after selecting kth test cases as <strong>θ̂<sub>j, k</sub></strong>; the total number of K test cases as <strong>t<sub>1, 2,…, K</sub></strong> and each test case’s feature as <strong>d<sub>k</sub></strong>; and the ground truth value of whether the student <em>j</em>’s code passes test case <em>k</em> or not as <strong>Y<sub>k, j</sub></strong>.</p>

<h3 id="mdp-setting">MDP Setting</h3>
<p>In our MDP setting, the environment contains two models: 1. Large Language Model (LLM<sub>e</sub>) 2.IRT-based model (IRT). The policy contains two models: 1. Large Language Model (LLM<sub>p</sub>) 2.Time-distributed long Short-Term Memory model (LSTM). During training, we use the same frozen LLM for LLM<sub>e</sub> and LLM<sub>p</sub> for simplicity. Figure 1 shows our MDP.</p>

<h3 id="state-definition">State Definition</h3>
<p>We represent our state as the LLM embeddings of the question statement, the solution code, and the test cases recommended so far minus the embeddings of the question statement, the student code, and the test cases recommended so far, <strong>S<sub>k</sub> = LLM<sub>e</sub>(q, a, t<sub>1..k</sub>) - LLM<sub>e</sub>(q, c<sub>j</sub>, t<sub>1..k</sub>)</strong>.</p>

<h3 id="action-definition">Action Definition</h3>
<p>Initially, We obtain a matrix <strong>Q</strong> containing the embeddings of all the test cases <strong>t<sub>1, 2,…,K</sub></strong> with LLM<sub>p</sub>, which is used for selecting the action. At every time step <em>k</em>, we first calculate the current hidden state <strong>h<sub>k</sub></strong> using LSTM with the state <strong>S<sub>k</sub></strong> as the input. Next, we project <strong>h<sub>k</sub></strong> to the space of test cases <strong>Q</strong> using a bi-linear projection matrix <strong>W</strong> to obtain the logits <strong>L’</strong>. Finally, we apply the softmax function to the logits <strong>L’</strong> to obtain a distribution over the test cases and choose the test case with the highest probability, which is <strong>A<sub>k</sub></strong>.</p>

<ul>
  <li><strong>Q</strong> = {LLM<sub>p</sub>(t<sub>k</sub>)}<sub>k ∈ {1..K}</sub></li>
  <li><strong>h<sub>k</sub></strong> = LSTM(<strong>S<sub>k</sub></strong>)</li>
  <li><strong>L’</strong> = <strong>h<sub>k</sub>WQ<sup>T</sup></strong></li>
  <li><strong>A<sub>k</sub></strong> = Argmax(<strong>L’</strong>)</li>
</ul>

<h3 id="reward-definition">Reward Definition</h3>
<p>Initially, we apply the IRT model to learn the features of all test cases and all students’ ground truth code qualities by maximizing <strong>P(Y<sub>k, j</sub> | θ<sub>j</sub>, d<sub>k</sub>)</strong>, which are used to calculate the reward.</p>

<p>If the selected test case <em>k</em> has not been selected before, we use all the selected test cases to update student <em>j</em>’s current code quality estimate <strong>θ̂<sub>j, k</sub></strong> by maximizing the <strong>P(Y<sub>k, j</sub> | θ̂<sub>j, k</sub>, d<sub>k</sub>)</strong>. Then we calculate <strong>1 / |θ<sub>j</sub> - θ̂<sub>j, k</sub>|</strong> as the reward, which is <strong>R<sub>k</sub></strong>. <strong>R<sub>k</sub></strong> measures how close the student <em>j</em>’s current code quality estimate is to the corresponding ground truth code quality. The smaller the difference, the bigger the reward. Otherwise, <strong>R<sub>k</sub></strong> = -10000. Giving a really big negative reward will force the agent to not select the same test case multiple times. We believe that the reward satisfies the Markovian property because it is solely based on the current state and action. Since the current state stores all the previously selected test cases.</p>

<h3 id="mdp-definition">MDP definition</h3>
<p>In summary, our MDP is defined as follows:</p>

<ul>
  <li>S: LLM<sub>e</sub>(<strong>q, a, t<sub>1..k</sub></strong>) - LLM<sub>e</sub>(<strong>q, c<sub>j</sub>, t<sub>1..k</sub></strong>)</li>
  <li>A: the set of all test cases - {t<sub>1</sub>..t<sub>K</sub>}</li>
  <li>P: <strong>P(LLM<sub>e</sub>(q, a, t<sub>1..k+1</sub>) | LLM<sub>e</sub>(q, a, t<sub>1..k</sub>), A<sub>k</sub>)</strong> = 1.0</li>
  <li>R:
    <ul>
      <li>-10000 if t<sub>k</sub> in {t<sub>1</sub>..t<sub>k-1</sub>}</li>
      <li><strong>1 / |θ<sub>j</sub> - θ̂<sub>j, k</sub>|</strong> otherwise</li>
    </ul>
  </li>
  <li><strong>d<sub>0</sub></strong>: LLM<sub>e</sub>(<strong>q, a</strong>) - LLM<sub>e</sub>(<strong>q, c<sub>j</sub></strong>)</li>
  <li>γ ∈ [0, 1), i.e., any value that is positive and smaller than 1.</li>
</ul>

<h2 id="implementation">Implementation</h2>

<h3 id="mdp">MDP</h3>
<p>We implement our custom environment using OpenAI Gymnasium and Stable Baselines 3. We need to override methods like <code class="language-plaintext highlighter-rouge">reset</code> and <code class="language-plaintext highlighter-rouge">step</code>.</p>

<h3 id="rl-algorithms">RL Algorithms</h3>

<p>We implement three algorithms <a href="https://openai.com/research/openai-baselines-ppo">PPO</a>, custom feature extractor PPO and custom policy (lstm bilinear policy with PPO).</p>

<ol>
  <li>PPO - We use the standard implementation of PPO using Stable Baselines 3.</li>
  <li>Custom Feature Extractor - Instead of using the standard feature extractor we use a custom LSTM network to embed the state representations.</li>
  <li>Custom Policy (LSTM Bilinear) - We modify the the policy to include the test case embeddings and a learnable bilinear layer that projects from the feature extraction (LSTM) space to the test case embeddings space.</li>
</ol>

<p>The code and its explanation can be found in my <a href="https://github.com/Nish-19/SB3-tutorial/tree/main">Github Repository</a>.Thanks to <a href="https://overbridge-wanyong.github.io/">Wanyong Feng</a> for collaborating with me on this project.</p>]]></content><author><name>Nischal Ashok Kumar</name></author><category term="Reinforcement Learning" /><category term="Stable Baselines 3" /><category term="Computerized Adaptive Testing" /><category term="Educational Data Mining" /><summary type="html"><![CDATA[]]></summary></entry><entry><title type="html">Applying to CS Ph.D. Programs</title><link href="https://nish-19.github.io/posts/2022/08/blog-post-5/" rel="alternate" type="text/html" title="Applying to CS Ph.D. Programs" /><published>2022-08-10T00:00:00-07:00</published><updated>2022-08-10T00:00:00-07:00</updated><id>https://nish-19.github.io/posts/2022/08/blog-post-5</id><content type="html" xml:base="https://nish-19.github.io/posts/2022/08/blog-post-5/"><![CDATA[<p><img src="https://user-images.githubusercontent.com/41947720/183966446-34c9bba2-9302-480f-9841-62ff6ead4c95.png" alt="graduate_image" /></p>

<p>Computer Science is one of the fastest-growing fields of study. Everyone has a different motivation for applying to graduate school, from progressing in their careers, learning advanced topics, and conducting research to exploring new places and opportunities. If you have decided to apply for CS Ph.D. programs, then you are in the right place. In this blog, we will talk about the process of application, tips to ace your application, and finally useful resources.</p>

<p><em>Disclaimer: The content of this blog reflects my opinion and may not be directly applicable to everyone. This is because people from diverse backgrounds and different stages of life apply to Ph.D. programs. I applied as a final year undergraduate CS student from India. My research area is ML and NLP and I applied to schools particularly in the United States.</em></p>

<h2 id="basic-pre-requisites">Basic Pre-requisites</h2>

<p>Here we will discuss the basic pre-requisites that one is expected to have accomplished for being eligible to apply for a Ph.D.</p>

<ol>
  <li><strong>Standardized tests</strong>: Different programs across the world may prescribe a different set of tests as an eligibility criterion for applying. However, from the perspective of the US, the GRE and TOEFL are considered the most popular.
    <ul>
      <li><strong>GRE</strong>: The GRE typically contains three parts to it, verbal, quantitative, and AWA (essay writing section). The verbal and quantitative parts are each scored for a total of 170 points and the AWA section is scored for 6 points. Most schools in the US do not require GRE for Ph.D. programs however, they are mostly mandatory for MS programs.</li>
      <li><strong>English Proficiency Test (TOEFL/ IELTS)</strong> : For most international students, an English proficiency test is required to prove that they can sustain academic life in the US. I took the TOEFL, and I believe that it is more popular than IELTS. The TOEFL has 4 sections, reading, listening, speaking, and writing each scored 30 points. Most universities set a cut-off value typically around 100 for the combined score to be eligible for applying. Also, several universities set special threshold scores for the sub-sections (for example UMass prescribes 26 in the speaking section).</li>
      <li>The standardized tests are merely used as a filtering criterion for Ph.D. students and do not play a major role in the application unless a candidate performs very poorly in it.</li>
    </ul>
  </li>
  <li>
    <p><strong>Undergrad Academic Records</strong>: Most universities take the undergraduate CGPA seriously while evaluating a candidate. Universities typically ask the students to provide both their overall CGPA and their major CGPA along with their class standings. Having a strong academic record (example top 5/10 in the class) can increase the chances of getting into the program, especially for students directly applying for their bachelor’s. A Master’s CGPA will be given more importance as compared to the undergrad CGPA for those students applying for Ph.D. positions after their masters. In all, if you are reading this blog in the early stages of your undergraduate studies, then it is recommended to maintain a great academic record.</p>
  </li>
  <li><strong>Research Experience</strong>: Research experience is the most important part while evaluating Ph.D. candidates. Ph.D. is a research degree, and CS being a very competitive field, universities expect you to have a good amount of research exposure before the application. Research experience can be gained by either working in academic settings under professors or working in industrial research laboratories. Your experience will shape the kind of work you do in your graduate studies and help the university to match your profile with current professors working there. Having publications as a first author in reputed conferences/ journals is a huge plus point in the application. Having great research experience can be used to overcome any deficiencies in the application.</li>
</ol>

<h2 id="process">Process</h2>

<p>Having known the basic pre-requisites for applying, let us look into the process of application.</p>

<ol>
  <li><strong>Networking</strong>: Contacting Professors and Ph.D. students - You must be wondering why a separate section is required on this. Academia is a small community and most researchers know each other working in their domain. So, how is this going to help you? Having an idea of which place to apply and under which professor is very important. Basically, as a Ph.D. applicant, you are applying to that school to work particularly under 3-4 professors working in your area of interest. It is very important to know if the professors you are aiming to work with are hiring students this year. If yes, what has been their hiring pattern over the past few years, do they prefer students straight out of undergrad or more experienced candidates out of residency programs, etc? All of this can be known by either emailing the professor or their Ph.D. students. Most professors who are looking for graduate students will respond to your email indicating your chances of getting into their program and may even set up an interview to know you better. So, what are the ways of networking?
    <ul>
      <li>Networking through conferences: Have you recently published a paper at a conference that is also attended by other members of the community? If so, make it a point to introduce yourself to your target professors and their students. Professors give huge importance to students who have already published in the venues where they generally publish. If you haven’t yet published at that conference but still have good research experience, you can work as a volunteer in the conference and get to talk to the grad students/ professors.</li>
      <li>Networking through mutual connections in the academia: If your current guide/ manager already knows professors in your area, then you can request them to introduce you to their connections who are hiring Ph.D. students. Again, this method is going to be very effective as direct recommendations within academia are considered very seriously.</li>
      <li>Networking on social media sites: Lastly, if none of the above points apply to you, you can still reach out to grad students on social media platforms like LinkedIn and Twitter with your questions. Most people would be happy to help.</li>
      <li>It is very important to know about the professor under whom you will be applying. Sometimes the professor of your choice may not be hiring graduate students for that year and you mentioning their name in the application may not help much.</li>
    </ul>
  </li>
  <li>
    <p><strong>SOP</strong>: Statement of Purpose is another important part of the application. Typically, universities allow students to write an SOP worth two pages of content with a font size of 12Pt. The SOP is your chance to talk to the admissions committee. You must elaborate on your motivation in your area of research. You must talk in detail about your past research experiences and how they have shaped your decision to pursue a Ph.D. It is fine for the Ph.D. SOP to have details and technical jargon - research-dense SOPs are generally given a preference. It is also very important to describe how your current research and plans align with the professors working in the university and the academic community in general.</p>
  </li>
  <li>
    <p><strong>LOR</strong>: Letters of Recommendation are one of the most important parts of the application. This is the part that you have the least control over. Most universities ask for a minimum of three LORs. For PhDs, it is recommended to have at least two LORs from academia. The third can be from the industry (preferably from someone in a research position). The LOR writers vouch for your ability as a researcher, mention the challenges you overcame while working with them and your soft skills. Strong LORs from your advisors highly increase your chances of consideration. In general, the academic standings of the LOR writers are considered seriously while evaluating their recommendations. Getting a strong letter from someone well-known in the community gives a huge boost to the application. However, it is generally recommended to go with recommenders who know you well and can give you a strong recommendation as compared to asking for a LOR from a well-known person who does not know you much.</p>
  </li>
  <li><strong>Interviews</strong>: Most professors interview potential students after reviewing their application. The interviews typically happen after the application deadline has passed i.e. during January. Based on my experience, interviews are mostly an informal conversation about your research. Interviews serve as a purpose for the professors to generally gauge your research aptitude and understand if you are a genuine candidate. It is important to do background study about the professor and know about their current projects and publications. This will help you to connect your projects with theirs which shows greater research fit and hence higher chances of acceptance.</li>
</ol>

<h2 id="general-tips">General Tips</h2>

<p>Now, we will see a few tips for acing the application process.</p>

<ol>
  <li>
    <p><strong>Start early</strong>: University portals start accepting applications from as early as September when the deadline is typically mid-December. Do not leave anything for the last moment. Start networking about 6 months before the application season i.e. the beginning of the year. Utilize the summer to finish any mandatory tests (GRE/TOEFL) and prepare the first draft of your SOP. Also, do let your letter writers know in advance (during the summer) of your plan to apply for a Ph.D. This will have them mentally prepared to give you recommendations on time.</p>
  </li>
  <li>
    <p><strong>Be organized</strong>: Maintain an excel sheet containing the program details you are applying to along with other information like the deadlines and the requirements. Also, keep a note of two-three professors from each school with whom you have already networked/ with whom you would like to work. This will help you in writing the “fit” part of your SOP where you describe why you are a right fit for the school.</p>
  </li>
  <li>
    <p><strong>Get SOPs reviewed by seniors</strong>: Graduate students with whom you have contact/ your advisors will be happy to review your SOP and provide suggestions. This can help you correct mistakes that went unnoticed.</p>
  </li>
  <li>
    <p><strong>Help your recommenders</strong>: Some letter writers may ask for a short draft or a bullet-wise summary of your work with them. They do this generally to save them time and to make sure they include every good point about you. Apart from this, send your letter writers an excel sheet consisting of the program details you are applying to along with the deadlines. Also, make sure to remind your recommenders to submit the recommendation as the deadline approaches.</p>
  </li>
  <li>
    <p><strong>Participate in the Pre-application review program</strong>: Some universities like UMass, Brown, and Columbia have a separate program which pairs applicants with current Ph.D. students. The current students provide valuable advice about different parts of the application and also the school in general. Do check them out!</p>
  </li>
</ol>

<h2 id="general-resources">General Resources</h2>

<p>Here are a few resources (blogs/ videos) that I found personally useful while applying:</p>

<ol>
  <li>Repository of advice:
    <ul>
      <li><a href="https://github.com/shaily99/advice">Exhaustive set of advice procured from various sources by Shaily Bhatt</a></li>
      <li><a href="https://martiansideofthemoon.github.io/2018/05/29/grad-resources.html">Kalpesh Krishna’s blog</a></li>
      <li><a href="https://martiansideofthemoon.github.io/2019/10/24/nlp-phd-survey.html">Student perspectives on applying to NLP programs</a></li>
      <li><a href="https://pg.ucsd.edu/PhD-application-tips.htm">5-minute Guide to Ph.D. applications (Philip Guo)</a></li>
      <li><a href="https://krrish94.github.io/blog/">Krishna Murthy’s set of blogs</a></li>
    </ul>
  </li>
  <li>Standardized Tests:
    <ul>
      <li><a href="https://martiansideofthemoon.github.io/2017/12/07/gre-toefl-preparation.html">Kalpesh Krishna’s GRE Guide</a></li>
      <li><a href="https://martiansideofthemoon.github.io/2017/12/07/gre-toefl-preparation-2.html">Kalpesh Krishna’s TOEFL Guide</a></li>
      <li><a href="https://www.gregmat.com/">GregMAT service</a></li>
    </ul>
  </li>
  <li>SOP:
    <ul>
      <li><a href="https://krrish94.github.io/blog/2020/gradschool-sop/">Krishna Murthy’s advice</a></li>
      <li><a href="https://blog.nelsonliu.me/2020/11/11/phd-personal-statement/">Nelson Liu’s Ph.D. SOP</a></li>
      <li><a href="https://nishanthjkumar.com/misc_files/MIT_SoP.pdf">Nishant J. Kumar’s SOP</a></li>
    </ul>
  </li>
  <li>LOR:
    <ul>
      <li><a href="https://krrish94.github.io/blog/2020/gradschool-letters/">Krishna Murthy’s advice</a></li>
      <li><a href="https://cs.brown.edu/~sk/Memos/Grad-School-Recos/">Prof. Shriram’s advice</a></li>
    </ul>
  </li>
  <li>General Videos/ Podcasts:
    <ul>
      <li><a href="https://www.youtube.com/watch?v=o8gnk0pWLhA">UMass Ph.D. application support program</a></li>
      <li><a href="https://soundcloud.com/nlp-highlights/133-phd-application-series-preparing-application-materials-with-nathan-schneider-and-roma-patel">Podcast - Roma Patel and Nathan Schneider</a></li>
      <li><a href="https://twitter.com/jbhuang0604/status/1446981455683407873">Pre-Application Review Programs List</a></li>
    </ul>
  </li>
  <li>After Getting Admits:
    <ul>
      <li><a href="https://www.cs.columbia.edu/wp-content/uploads/2019/03/Get-Advisor.pdf">Questions to ask your advisor on visit days</a></li>
    </ul>
  </li>
</ol>

<h2 id="summary">Summary</h2>

<p>Applying for a Ph.D. program can be a daunting task. From deciding which schools to apply for to managing the SOPs and LORs is surely a stressful process. Having said that, approaching systematically by preparing well before the application can help ease the tension and guide you in the right direction. Hope the blog’s content and the resources linked here are useful to you. All the best for your application!</p>]]></content><author><name>Nischal Ashok Kumar</name></author><category term="Graduate School" /><category term="Ph.D. Application Advice" /><summary type="html"><![CDATA[]]></summary></entry><entry><title type="html">BERTology Transfer Learning in Natural Language Processing</title><link href="https://nish-19.github.io/posts/2021/02/blog-post-4/" rel="alternate" type="text/html" title="BERTology Transfer Learning in Natural Language Processing" /><published>2021-02-14T00:00:00-08:00</published><updated>2021-02-14T00:00:00-08:00</updated><id>https://nish-19.github.io/posts/2021/02/blog-post-4</id><content type="html" xml:base="https://nish-19.github.io/posts/2021/02/blog-post-4/"><![CDATA[<table>
  <thead>
    <tr>
      <th style="text-align: center"><img src="https://user-images.githubusercontent.com/41947720/107882848-9c291f80-6f11-11eb-8dc1-f33ea0e2f428.png" alt="initial_googleai" /></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="text-align: center"><em>BERT: Google AI</em></td>
    </tr>
  </tbody>
</table>

<p>Representation Learning is of prime importance in machine learning tasks; it is ultimately the input data representations that play a significant role in determining the model’s performance. There are scenarios where learning representations of the input data require transferring of knowledge from related but different tasks. This is where transfer learning comes in. Transfer Learning helps us utilize a more generalizable set of features and fine-tune them for the downstream task. To know more about transfer learning, please go through my blog <a href="https://nish-19.github.io/Transfer-Learning/">linked here</a></p>

<p>In my recent NLP work, I have been using BERT and related models for certain downstream tasks like text classification on domain specific data. I am writing this blog with the motive of introducing you to the recent boom in transfer learning in natural language processing with the advent of architectures like BERT.</p>

<p>I will focus on the description of BERT and talk about using them in your works using Hugging Face.</p>

<h2 id="motivation">Motivation</h2>

<table>
  <thead>
    <tr>
      <th style="text-align: center"><img src="https://user-images.githubusercontent.com/41947720/107882859-aba86880-6f11-11eb-9bc2-182fcda289f3.png" alt="transformers" /></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="text-align: center"><em>Transformers: Image from Jay Ammar</em></td>
    </tr>
  </tbody>
</table>

<p>The 2017 OpenAI’s paper <a href="https://arxiv.org/abs/1706.03762">“Transformers: Attention is all you need”</a> brought about a revolution in the field of deep learning in natural language processing by performing better than traditional recurrent neural network architectures like LSTMs and GRUs. In general, transformers are seen to handle long-term dependencies in the text better than LSTMs, which led to them performing significantly better than LSTM based architectures on tasks like Machine Translation.</p>

<p>Transformers are the reason for the birth of BERT and the series of other architectures that follow. Motivated by the developments in Computer Vision, NLP researchers were eyeing to create a model capable of generating better input text representations that could be used directly for downstream tasks.</p>

<p>Using the decoder layer of transformers, we could train it for language modeling, i.e., next word prediction task. We can train the stack of decoders of the Transformers on a massive corpus of data and allow it to learn the “context” of the language. This trained transformer decoder stack can then be used for obtaining better representations of input data for downstream tasks like text classification.</p>

<h2 id="entry-of-bert">Entry of BERT</h2>

<table>
  <thead>
    <tr>
      <th style="text-align: center"><img src="https://user-images.githubusercontent.com/41947720/107882867-ba8f1b00-6f11-11eb-977e-d70bf217df0f.png" alt="bert_pretraining" /></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="text-align: center"><em>BERT Pre-Training and Fine-Tuning Procedure</em></td>
    </tr>
  </tbody>
</table>

<p>Well, everything fine until now. But there is a catch. Transformer’s decoder architecture mentioned above doesn’t learn “bi-directional” contextualized embeddings, making it less sophisticated than ELMo (Bi-Directional LSTM based architecture for generating dynamic contextualized embeddings).</p>

<p>Well, BERT said why not combine the idea of both ELMo and Transformers?</p>

<p>BERT stands for Bidirectional Encoder Representations from Transformers.
It uses the transformer encoder part and trains a “masked language model” randomly masking 15% of its input tokens. The task is to predict these tokens correctly.</p>

<p>BERT introduces another task in the pre-training – “The next sentence prediction” for incorporating sentence level knowledge.
The task here is to determine if the second sentence follows the first one. For doing so, BERT introduces its special way of tokenization. BERT’s first token is the <CLS> token, which contains information about the next sentence classification task. Apart from this, the two sentences are separated by a special <SEP> token.</SEP></CLS></p>

<p>In addition to the single-sentence classification task and single sentence tagging task, this additional pre-training mechanism for next sentence prediction allows BERT to solve various problems. These include sentence pair classification tasks like Natural Language Inference tasks and question answering tasks.</p>

<table>
  <thead>
    <tr>
      <th style="text-align: center"><img width="690" alt="bert_types" src="https://user-images.githubusercontent.com/41947720/107882874-c7137380-6f11-11eb-992e-07464561673f.png" /></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="text-align: center"><em>BERT Paper showing different tasks</em></td>
    </tr>
  </tbody>
</table>

<h2 id="using-bert">USING BERT</h2>

<p>If you have been wondering when do I get to learn how to use BERT in my project, then thanks for hanging on until this stage. Here we will talk about two popular ways of using BERT: -</p>

<ol>
  <li>For Generating Contextualized Embeddings</li>
  <li>For Fine-Tuning.</li>
</ol>

<p>Before diving into it, let us set up our environment for running BERT.</p>

<p>We will use both Pytorch and Tensorflow 2.0 with Hugging Face for running BERT.
Hugging Face is a NLP startup which release open source NLP state-of-the-art models which can be used by anyone.</p>

<table>
  <thead>
    <tr>
      <th style="text-align: center"><img src="https://user-images.githubusercontent.com/41947720/107882891-d692bc80-6f11-11eb-807d-ebc50d6d8bd4.png" alt="huggingface" /></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="text-align: center"><em>Hugging Face</em></td>
    </tr>
  </tbody>
</table>

<p>These models run with the support of deep learning libraries like Pytorch or Tensorflow 2.0.</p>

<p>Having known this, let us install the transformers module which contains the actual implementation BERT and related models.
pip install transformers.</p>

<p>For installing Pytorch -&gt; “pip install pytorch”</p>

<p>For installing Tensorflow 2.0 -&gt; pip install tensorflow</p>

<p>(You could do conda install as well, depending on your virtual environment). (Note: Using anaconda is highly recommended).</p>

<p>Here, I will highlight the main steps involved in running BERT the full code is made available on GitHub along with a dataset to experiment on here.</p>

<h3 id="tokenization">TOKENIZATION:</h3>

<table>
  <thead>
    <tr>
      <th style="text-align: center"><img src="https://user-images.githubusercontent.com/41947720/107882900-e3171500-6f11-11eb-8d87-909addd2da98.png" alt="tokenization" /></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="text-align: center"><em>Tokenization Procedure in BERT</em></td>
    </tr>
  </tbody>
</table>

<p>After data pre-processing, tokenization is the first step of all natural language processing tasks. We break the sentences to words/ sub-word chunks and use this for generating features that can be used to train the model.</p>

<p>The Hugging Face Transformers comes with its own tokenizer which varies as per the BERT model you are using.</p>

<p>The entire process of tokenization can be further divided into three parts: -</p>

<ol>
  <li>Converting the sentence/ sentence pair into numerical tokens.</li>
  <li>Padding the sequences to a maximum length.</li>
  <li>Defining the attention masks and the token_type_ids</li>
</ol>

<p><strong>Attention masks</strong> – These indicate whether the token corresponds to a word or refers to padding.</p>

<p>For normal words 1 is used as masking number. For padding tokens 0 is used as the masking token.</p>

<p><strong>Token_Type_Ids</strong> – This is a special id which marks the difference between the pair of sentences in case of a sentence pair input. The first sentence from the <CLS> token till the <SEP> is represented by 0 and the second sentence uptil <SEP> is represented by 1.</SEP></SEP></CLS></p>

<table>
  <thead>
    <tr>
      <th style="text-align: center"><img width="533" alt="code" src="https://user-images.githubusercontent.com/41947720/107883661-34290800-6f16-11eb-9d61-efe69b3e8ae2.png" /></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td style="text-align: center"><em>Code Snippet for automatic Tokenization. For manual tokenization check my GitHub link</em></td>
    </tr>
  </tbody>
</table>

<p>Having finished the tokenization phase we can now either train a classifier on top of the embeddings obtained from BERT or we could tune the entire BERT architecture for about 2-4 epochs. In general, it is observed that fine-tuning gives better performance over using the embeddings directly.</p>

<p><a href="https://github.com/Nish-19/BERT_Tutorial">The entire code for this can be found on my GitHub repository here.</a> Please do check it out.</p>

<p>The repository contains two codes -</p>
<ol>
  <li>bert_embeddings.py (Making use of embeddings for classification) (Coded in Hugging Face with Tensorflow 2.0)</li>
  <li>bert_fine_tune.py (Fine tuning BERT on downstream task) (Coded in Hugging Face with Pytorch)</li>
</ol>

<p>References and Acknowledgements:</p>
<ol>
  <li>Jay Ammar’s Blogs on Transformers and BERT
    <ul>
      <li><a href="http://jalammar.github.io/illustrated-transformer/">Illustrated Transformer</a></li>
      <li><a href="http://jalammar.github.io/illustrated-bert/">Illustrated BERT</a></li>
      <li><a href="http://jalammar.github.io/a-visual-guide-to-using-bert-for-the-first-time/">Using BERT for The First Time</a></li>
    </ul>
  </li>
  <li><a href="https://arxiv.org/abs/1706.03762">Transformers: Attention is All you need</a></li>
  <li><a href="https://arxiv.org/abs/1810.04805">BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding</a></li>
</ol>]]></content><author><name>Nischal Ashok Kumar</name></author><category term="BERT/ Transformers" /><category term="NLP" /><summary type="html"><![CDATA[BERT: Google AI]]></summary></entry><entry><title type="html">IIT-Patna Academic Alexa</title><link href="https://nish-19.github.io/posts/2020/12/blog-post-3/" rel="alternate" type="text/html" title="IIT-Patna Academic Alexa" /><published>2020-12-22T00:00:00-08:00</published><updated>2020-12-22T00:00:00-08:00</updated><id>https://nish-19.github.io/posts/2020/12/blog-post-3</id><content type="html" xml:base="https://nish-19.github.io/posts/2020/12/blog-post-3/"><![CDATA[<p><img width="547" alt="basic" src="https://user-images.githubusercontent.com/41947720/102855734-2e013880-444b-11eb-82ba-7c5b845dbdb1.png" /></p>

<p>In this post, I will take you through the Chatbot IIT-Patna Academic Alexa which is a sentiment-aware intelligent information retrieval based system for the academic portal of IIT-P.</p>

<p>Chatbots are one of the best applications of Natural Language Processing in improving human-computer interaction. The idea of the first chatbot was conceived in 1964, and since then, the development and usage of chatbots has sky-rocketed, owing to the advancements in computing, deep learning and deployable machine learning. Inspired from many such applications we build a novel chatbot for information retrieval for IIT-Patna’s academic data.</p>

<h2 id="motivation">Motivation</h2>

<p>Imagine you have a huge database consisting of the academic and personal details of students enrolled in your college/ organization. Now, we want to retrieve certain data like the marks of a student in a particular subject, or the credits of a subject, the number of subjects taught in a particular year etc. How do we generally do it? Simple! Just open it in a csv file and search for the parameters manually.
As you have guessed that this will be a tedious and unfeasible task.</p>

<p>Now, what if we store the database in the form of MySQL relational tables and then write appropriate queries for performing the task?
Sounds easy right? But is everyone computer literate? Can everyone write MySQL queries for retrieval of information for the data?</p>

<p>To address this task we set out to come up with a chatbot which takes Natural Language of the users as input and converts it into the appropriate SQL query and automatically fetches and displays the output. We design an entire chatbot pipeline for performing the given task.</p>

<h2 id="chatbot-pipeline">Chatbot Pipeline</h2>

<p><img src="https://user-images.githubusercontent.com/41947720/102854443-8f73d800-4448-11eb-9648-302559da675c.png" alt="pipeline_diagram" /></p>

<p>Components of the Custom-Designed Pipeline of IIT-P Academic Alexa: -</p>
<ol>
  <li>Input Module</li>
  <li>Sentence Classifier</li>
  <li>NL to SQL Engine</li>
  <li>NLTK Regular Chat</li>
  <li>Sentence Similarity Module</li>
  <li>Feedback Module</li>
  <li>Continual Learning System</li>
  <li>Sentiment Analyzer</li>
</ol>

<p><img style="float: right;" width="382" alt="pipeline_classifier" src="https://user-images.githubusercontent.com/41947720/102853387-43279880-4446-11eb-9979-862c5c632847.png" /></p>

<h3 id="sentence-classifier-module">Sentence Classifier Module</h3>

<ul>
  <li>Each query to the chatbot belongs to either database query or non-database query category.</li>
  <li>Database queries are those which are addressed for information retrieval from the database.</li>
  <li>Non-Database queries are those which conduct normal-conversation like Hi, How are you? Thank You etc.</li>
  <li>Sentence Classifier Module is Deep Learning Based Binary Classifier for classifying as “Database” or “Non-Database” query</li>
  <li>Multi-Channel Convolutional Neural Network Model coded in Tensorflow</li>
  <li>Self-Prepared and annotated the train and the test set</li>
  <li>Model used for real-time inferencing (lightweight for deployability)</li>
  <li>Capable of adapting to Continual Learning (or Online Learning Environment)</li>
</ul>

<h3 id="model-specifications">Model Specifications</h3>

<p><img width="895" alt="multicnn_diagram" src="https://user-images.githubusercontent.com/41947720/102853797-0dcf7a80-4447-11eb-9ce2-3a4fbef285a4.png" /></p>

<h4 id="motivation-of-using-multi-cnn">Motivation of using Multi-CNN</h4>

<p><img width="178" alt="multicnn_demonstration" src="https://user-images.githubusercontent.com/41947720/102853852-28095880-4447-11eb-90de-04e59b54deb5.png" /></p>

<ul>
  <li>CNNs capture local features of the input</li>
  <li>Input to sentence classifier in our case depends of local feature mapping</li>
  <li>Local features in textual context can be visualized as n-gram based features</li>
  <li>Inherit n-gram feature modelling in multi-cnn is hence useful.</li>
</ul>

<p>The sentence classifier mentioned here is trained on the self-procured and annotated train set and evaluated on the test set. It acheives about 93% accuracy.</p>

<p><img style="float: right;" width="356" alt="pipeline_nlsql" src="https://user-images.githubusercontent.com/41947720/102853984-7e769700-4447-11eb-97f5-8035c09ad29c.png" /></p>

<h3 id="nl-to-sql-engine">NL to SQL Engine</h3>

<p>Our module: -</p>
<ul>
  <li>Converts Natural Language Data into SQL (Structured-Query-Language) for information retrieval from the database</li>
  <li>Works on self-developed algorithms based on the “Dependency-Tree-Parser” of the natural language query</li>
  <li>Works on questions of type: -
    <ul>
      <li>List</li>
      <li>Which</li>
      <li>What</li>
      <li>How Many</li>
      <li>Who</li>
    </ul>
  </li>
  <li>Algorithm proposed here is extendable</li>
</ul>

<p>For coming up with the idea, the following steps were performed: -</p>

<ul>
  <li>Carried out literature search on traditional methods for NL to SQL conversion</li>
  <li>NL to SQL is an open-ended research problem in the field of lexical semantics and semantic parsing</li>
  <li>Decided to use the “Syntax” and “Lexical Semantics” of the natural language data</li>
  <li>Hypothesized about using Part-of-Speech-Tagging</li>
  <li>Investigated the problem by using “Dependency Tree Parsers”</li>
  <li>Developed a basic tree-parsing algorithm for the questions.</li>
  <li>Implemented a DFS (Depth-First-Search) approach for certain type of questions</li>
</ul>

<p>The NL-SQL part of the project was done by me and my classmate Vaibhav.</p>

<p>Sample pseudocode for “list question” conversion is given below</p>

<p><img width="910" alt="list_question" src="https://user-images.githubusercontent.com/41947720/102854180-02308380-4448-11eb-9c76-4bf842c465f8.png" /></p>

<p>Implementation Details</p>

<ul>
  <li>Explored different options for libraries like nltk and spaCy</li>
  <li>Decided to use spaCy library for obtaining the Dependency Tree of the natural language query</li>
  <li>spaCy is
    <ul>
      <li>A Free Open Source Natural Language Processing Library in Python</li>
      <li>Offers modules for NER, POS, Sentence Similarity and Text Classification</li>
    </ul>
  </li>
  <li>Reasons for using spaCy
    <ul>
      <li>Lightweight and easy to use</li>
      <li>Easily integratable with python</li>
      <li>Provides robust results as compared to traditional text processing libraries.</li>
    </ul>
  </li>
  <li>spaCy offers the fastest syntactic parser in the world of accuracy within 1% of the best available <a href="https://www.aclweb.org/anthology/P15-1038.pdf">(Choi et al., 2015)</a></li>
</ul>

<h3 id="python-sql-connector">Python SQL Connector</h3>

<ul>
  <li>Part of the NL-SQL converter engine</li>
  <li>Takes as input the SQL query generated from the natural language data</li>
  <li>Establishes connection with the MySQL server in the local machine (where the database is stored)</li>
  <li>Fetches and Processes the returned tuple structure for forming the appropriate output</li>
</ul>

<p>Implementation Details:</p>
<ul>
  <li>Use mysql connector: a standard database driver provided by MySQL</li>
  <li>Step 1: Authorization</li>
  <li>Step 2: Creating a cursor pointing to the database</li>
  <li>Step 3: Provide the query in form of string and process the returned output</li>
</ul>

<p><img style="float: right;" width="369" alt="pipeline_nltk" src="https://user-images.githubusercontent.com/41947720/102854729-204ab380-4449-11eb-8504-fffc4742c87f.png" /></p>

<h3 id="nltk-chat">NLTK Chat</h3>

<ul>
  <li>Based on NLTK (Natural Language Toolkit) library</li>
  <li>Chat Provision for Regular (Non-Database) queries like Hello, Thank You etc.</li>
  <li>Based on simple regex (Regular Expression) matching of queries</li>
  <li>Pairs variable coded by the programmer contains predefined regex query -&gt; output mapping</li>
  <li>Reflections variable contains pronouns mapping from question to answer</li>
  <li>Lightweight and easy to use</li>
  <li>Helps make the chatbot more interesting by incorporating daily life conversations</li>
</ul>

<p><img style="float: right;" width="374" alt="pipeline_feedback" src="https://user-images.githubusercontent.com/41947720/102854801-4b350780-4449-11eb-99dd-4d41adb30bd1.png" /></p>

<h3 id="feedback-module">Feedback Module</h3>

<ul>
  <li>Practical software systems cannot be infallible. Feedback is the means of striving towards perfection.</li>
  <li>Two steps:-
    <ul>
      <li>Sentence Similarity</li>
      <li>Data Collection</li>
    </ul>
  </li>
</ul>

<h4 id="sentence-similarity-module">Sentence Similarity Module</h4>

<p><img width="902" alt="sentence_similarity" src="https://user-images.githubusercontent.com/41947720/102854893-846d7780-4449-11eb-9008-1902fb0a8d82.png" /></p>

<h4 id="feedback-data-collection">Feedback Data Collection</h4>

<p>Continuous data is collected from the users/ testers</p>
<ol>
  <li>Sentence Similarity module: -
    <ul>
      <li>Misclassification of input query is tackled</li>
      <li>The specific text followed by the feedback label is recorded</li>
      <li>Feedback label is either database or non-database tag labelled by the user</li>
    </ul>
  </li>
  <li>NL-SQL Module:-
    <ul>
      <li>NL-SQL misconversion is tackled</li>
      <li>The input query is recorded in a csv file and the file is forwarded to the code maintainer</li>
    </ul>
  </li>
  <li>NLTK Chat Module: -
    <ul>
      <li>Tackles Regular chat which is not present in the pre-defined chat pair</li>
      <li>The input query is recorded in a csv file and the file is forwarded to the code maintainer</li>
    </ul>
  </li>
</ol>

<h4 id="continual-learning-online-training">Continual Learning/ Online Training</h4>

<ul>
  <li>Ability of a Machine Learning model to learn continually from a stream of data</li>
  <li>Is of prime importance in production environments</li>
  <li>User feedback is stored in a separate csv file</li>
  <li>Sentence Classifier module learns from the collected feedback data at regular intervals of time</li>
  <li>The classifier learns with time and hence becomes better</li>
</ul>

<p><img width="372" alt="pipeline_sentiment" src="https://user-images.githubusercontent.com/41947720/102855074-e9c16880-4449-11eb-93cb-69bbfc111eb6.png" /></p>

<h3 id="sentiment-analysis-module">Sentiment Analysis Module</h3>

<ul>
  <li>We carry out sentiment analysis of all users using the chatbot platform</li>
  <li>Sentiment of students when chatting with the chatbot can give various insights
    <ul>
      <li>Mental state of the student</li>
      <li>Overall satisfaction of group of students with the results/marks obtained</li>
    </ul>
  </li>
</ul>

<p>Implementation done using Vader-Sentiment-Analysis</p>

<ul>
  <li>VADER is a rule-based sentiment analysis tool  which does lexicon based scoring</li>
  <li>Sentiment scores are between -1 and 1</li>
  <li>Sentiment score of:
    <ul>
      <li>0 is neutral</li>
      <li>Less than -0.05 is negative</li>
      <li>Greater than 0.05 is positive</li>
    </ul>
  </li>
  <li>Sentiment of all sentences are averaged to determine the overall sentiment of the user</li>
</ul>

<p>Hence this completes the summary of all the modules used in the chatbot pipeline.</p>

<p><img width="545" alt="db_query" src="https://user-images.githubusercontent.com/41947720/102855769-3e191800-444b-11eb-8b4e-61ce38d36591.png" /></p>

<p>This was a team project and here in this blog I have taken you through my part of the project. There is much more to this like the final interface, data analysis etc. which was done by my classmates at IIT-Patna.</p>

<p><a href="https://github.com/Nish-19/IIT_Patna_Academic_Chatbot">You can find the code for this project on GitHub here.</a></p>

<p>Stay tuned for more ML and DL content!</p>]]></content><author><name>Nischal Ashok Kumar</name></author><category term="Chatbot" /><category term="NLP" /><summary type="html"><![CDATA[]]></summary></entry><entry><title type="html">Unlabeled Data for Adversarial Robustness</title><link href="https://nish-19.github.io/posts/2020/07/blog-post-2/" rel="alternate" type="text/html" title="Unlabeled Data for Adversarial Robustness" /><published>2020-07-20T00:00:00-07:00</published><updated>2020-07-20T00:00:00-07:00</updated><id>https://nish-19.github.io/posts/2020/07/blog-post-2</id><content type="html" xml:base="https://nish-19.github.io/posts/2020/07/blog-post-2/"><![CDATA[<p><img src="https://user-images.githubusercontent.com/41947720/87966557-0a704580-cadb-11ea-965a-4b7d1046fc2f.png" alt="image" />
<em>Effect of adversarial perturbations on natural input - Misclassification of an image (which hasn’t changed in human’s perspective)</em></p>

<p>This blog post talks about using Unlabeled data for improving Adversarial Robustness in deep neural networks. This post is a summary of the following works: -</p>
<ol>
  <li><a href="https://arxiv.org/pdf/1901.09960.pdf">Using Pre-training can improve model robustness</a> (ICML 2019)</li>
  <li><a href="https://arxiv.org/abs/1905.13736">Unlabeled data improves adversarial robustness</a> (NeurIPS 2019)</li>
  <li><a href="https://arxiv.org/abs/1905.13725">Are labels required for improving adversarial robustness?</a> (NeurIPS 2019)</li>
</ol>

<h2 id="brief-precursor-to-using-unlabeled-data-for-adversarial-robustness">Brief Precursor to using unlabeled data for adversarial robustness</h2>

<p>Adversarial Robustness, in general, deals with the question whether we can develop classifiers that are robust to (test time) perturbations of their input, by an adversary intending to fool the classifier. This is of prime importance in critical applications of deep learning like cancer recognition systems, self-driving cars etc. where the scope of error is almost nil. In the recent years there has been significant developments in creating both adversaries and defenses against them.</p>

<p><a href="https://papers.nips.cc/paper/7749-adversarially-robust-generalization-requires-more-data">Schmidt et al</a> had showed in their work that there is a sample complexity gap in achieving the same robust accuracy as clean accuracy for a classification task using cifar-10 as the dataset.</p>

<p><img src="https://user-images.githubusercontent.com/41947720/87968037-6c31af00-cadd-11ea-9a95-90e5f8da4ca0.png" alt="image" /></p>

<p>Hence from his work we can conclude that there is a need for additional data for improving adversarial robustness. This worked served as a motivation to the papers we will be discussing in this blog. The following researchers started wondering how to make up for this additional data to bridge the sample complexity gap.</p>

<h2 id="using-pre-training-improves-adversarial-robustness">Using Pre-Training Improves Adversarial robustness</h2>

<p>This paper introduces the concept of Adversarial Pre-training. This is based on the following concepts: -</p>
<ol>
  <li>The problem of requirement of more task specific data can be solved using pre-training (a typical transfer learning scenario)</li>
  <li>Data from a different distribution can be beneficial for a different task (Huh et al)</li>
</ol>

<h3 id="method-used">Method used</h3>

<ul>
  <li>Adversarial pre-training on downsampled (to 32X32 size) ImageNet(1000 class) dataset with 10 step PGD with eps = 8/255 (l-infinity).</li>
  <li>Fine tuning with Cifar-10 dataset using pgd-10 with eps = 8/255 for 5 epochs</li>
  <li>Finally, evaluating with cifar-10 using pgd-20 with eps = 8/255 (l-infinity)
Note - They use wrn-28-10 for all their experiments</li>
</ul>

<h3 id="results">Results</h3>

<p><img src="https://user-images.githubusercontent.com/41947720/87968988-eca4df80-cade-11ea-985c-1a585f6210dc.png" alt="image" />
From the results obtained by them we can observe that the clean accuracy has almost remained the same whereas the adversarial accuracy has significantly increased (by 12%). Hence from this work we can conclude that adversarial features can robustly transfer across data distributions.</p>

<h2 id="unlabeled-data-improves-adversarial-robustness">Unlabeled Data improves Adversarial robustness</h2>

<p>This paper addresses the following questions -</p>
<ul>
  <li>How can we account for additional data for improving robustness?</li>
  <li>How to get additional labelled data?
<em>Labelling may be an expensive process</em></li>
</ul>

<p>The solution to the questions is a Semi-Supervised Adversarial Training Algorithm</p>

<p>Here they propose an algorithm Robust Self Training (RST) which is based on : -</p>
<ol>
  <li>Taking unlabeled data and generating pseudo labels from them (using a network pre-trained with the labeled data)</li>
  <li>Mixing the unlabeled data and the labeled data in a definite proportion.</li>
  <li>Performing adversarial training (<a href="https://arxiv.org/pdf/1901.08573.pdf">TRADES</a>) on this dataset.</li>
</ol>

<p>The reasoning for using unlabeled data for bridging the sample complexity gap is: -</p>
<ul>
  <li>Labeling Data is generally an expensive and tedious process.</li>
  <li>Adversarial Robustness requires the predictions to be stable around naturally occurring inputs. Achieving this doesn’t really require labels.</li>
</ul>

<h3 id="rst-algorithm-pseudocode">RST Algorithm pseudocode</h3>

<p><img src="https://user-images.githubusercontent.com/41947720/87969963-aea8bb00-cae0-11ea-8c9a-40ac2c8b2b0d.png" alt="image" /></p>

<p>Here, Lstandard is the cross-entropy loss and Lrobust is the <a href="https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence">KL</a> loss (as used in TRADES)</p>

<p>Note - Here cifar-10 is used as the labeled dataset containing 50K training samples. The unlabeled data is procured from the 80M Tiny Images dataset following a definite procedure. Total 500K unlabeled data is procured.</p>

<h3 id="results-1">Results</h3>

<p><img src="https://user-images.githubusercontent.com/41947720/87970323-31ca1100-cae1-11ea-849a-3261f399a9b9.png" alt="image" /></p>

<p><em>The results are reported using wrn-28-10 with learning_scheduler cosine and unsupervised_fraction - 0.5 (i.e. each epoch contains half labeled and half unlabeled data)</em></p>

<p>We can observe that the RST model performs better than the other models on all the attacks, also it gets the highest accuracy on clean samples as well (89.7%)</p>

<h2 id="are-labels-required-for-improving-adversarial-robustness">Are Labels Required for improving Adversarial Robustness</h2>

<p>Like the previous work, this work also focuses on using unlabeled data for improving adversarial robustness.</p>

<p>The main contributions of this work are: -</p>
<ol>
  <li>Proposed UAT (Unsupervised Adversarial Training) method to make use of unlabeled data.</li>
  <li>Proved that unlabeled data can be competitive to labelled data for bridging the sample complexity gap in Schmidt et al.</li>
  <li>New state-of-art on CIFAR-10 using uncurated unlabeled data.</li>
</ol>

<p>The motivation behind this work is: -</p>
<ol>
  <li>Labelled data is expensive</li>
  <li>Adversarial robustness depends on the smoothness of the classifier which can be determined by unlabeled data.</li>
  <li>Only a small amount of labelled data is needed for standard generalization.</li>
</ol>

<p>Here, they propose three variants of the UAT algorithm and experiment with all three of them.</p>

<p><img src="https://user-images.githubusercontent.com/41947720/87971125-786c3b00-cae2-11ea-9c6f-5837d8f5c48e.png" alt="image" /></p>

<p>These loss notations are useful for understanding the pseudocodes below. As from the losses, both the losses are making use of the the adversarial perturbed input (by considering the l-infinity norm ball)</p>

<h3 id="algorithm-uat-ot">Algorithm UAT-OT</h3>

<p><img src="https://user-images.githubusercontent.com/41947720/87971483-0ba57080-cae3-11ea-9e30-8da4956e9009.png" alt="image" /></p>

<h3 id="algorithm-uat-ft">Algorithm UAT-FT</h3>

<p><img src="https://user-images.githubusercontent.com/41947720/87971531-1b24b980-cae3-11ea-9c16-4c0937b12aa1.png" alt="image" /></p>

<h3 id="algorithm-uat">Algorithm UAT++</h3>

<p><img src="https://user-images.githubusercontent.com/41947720/87971577-2c6dc600-cae3-11ea-940e-c88c017d03fa.png" alt="image" /></p>

<p>Note the UAT++ algorithm is very similar to the RST algorithm of the previous paper except that in UAT++ both the losses (entropy and KL) are making use of the the adversarial perturbed input (by considering the l-infinity norm ball), whereas in RST only KL minimizes with adversarial input.</p>

<p>Also, here the unlabeled dataset is taken from the same labeled dataset but without considering the labels.</p>

<p><img src="https://user-images.githubusercontent.com/41947720/87971803-88384f00-cae3-11ea-8284-dadf0f41a486.png" alt="image" /></p>

<p>Here, we can see that the UAT++ algorithm performs as good as a supervised-oracle (a model which is trained with labels for the unlabeled data also). This proves that unlabeled data is competitive to labeled data for adversarial robustness.</p>

<h2 id="conclusion">Conclusion</h2>

<p>Hence we have seen how unlabeled data can be used to improve adversarial robustness by studying the above three papers. For more details regarding this it is recommended to read the original papers. For a general idea about adversarial robustness one can refer <a href="https://adversarial-ml-tutorial.org/introduction/">here</a>.</p>

<p>Stay tuned for more ML and DL content!</p>]]></content><author><name>Nischal Ashok Kumar</name></author><category term="Deep Learning" /><category term="Adversarial Robustness" /><summary type="html"><![CDATA[Effect of adversarial perturbations on natural input - Misclassification of an image (which hasn’t changed in human’s perspective)]]></summary></entry><entry><title type="html">Mathematics for ML and DL</title><link href="https://nish-19.github.io/posts/2020/05/blog-post-1/" rel="alternate" type="text/html" title="Mathematics for ML and DL" /><published>2020-05-26T00:00:00-07:00</published><updated>2020-05-26T00:00:00-07:00</updated><id>https://nish-19.github.io/posts/2020/05/blog-post-1</id><content type="html" xml:base="https://nish-19.github.io/posts/2020/05/blog-post-1/"><![CDATA[<p><img src="https://user-images.githubusercontent.com/41947720/82878340-000d5180-9f59-11ea-8293-8d653df784e7.png" alt="image" /></p>

<p>Ever wondered what goes on in neural networks? Ever tried to calculate the gradients of the loss function after each pass? If yes, then you must have realized the role played by mathematical concepts here. If no, then you are at the right place.</p>

<p>In this blog post we will see the topics of Mathematics that are the most crucial for understanding and appreciating machine learning algorithms. Machine Learning has become very popular nowadays with developers and undergraduate college students, given the plethora of courses out there and the ease of building and running neural networks (thanks to google colab!). But, how many of these “machine-learners” actually understand the maths behind what is going on? Is it important? Well, not so much if you just want to play around with it, but an emphatic yes if you want to pursue research projects or come up with your new ideas.</p>

<p>Having said this, let’s dive into our topics.</p>

<h2 id="linear-algebra">Linear Algebra</h2>

<p><img src="https://user-images.githubusercontent.com/41947720/82879763-0bfa1300-9f5b-11ea-9657-fa40c4225fcc.png" alt="image" /></p>

<p>Linear algebra is the study of vectors (n-dimensional in general) and the operations associated with them. In the context of Machine Learning, we use vectors, matrices and tensors to concisely represent data. By doing so, we can eliminate confusions and write the equations occurring in the ML models in a succinct and short-hand form.</p>

<p><img src="https://user-images.githubusercontent.com/41947720/82880622-516b1000-9f5c-11ea-9d17-fd289a03d65c.png" alt="image" /></p>

<p>The above image represents the computations taking place in a single neuron. We are calculating the weighted sum of the inputs and passing it through a non-linearity (function f() here).</p>

<p><img src="https://user-images.githubusercontent.com/41947720/82881001-bf173c00-9f5c-11ea-9d51-c28f6098c7ee.png" alt="image" /></p>

<p>We can observe the compact mathematical representation of the  equation in the above image. Here b + x.w is obtained by matrix multiplications and addition which is a topic under Linear algebra.</p>

<p>Now, let’s look at a bigger picture of the entire neural network from LA’s perspective (LA - Linear Algebra and not Los Angeles 😉).</p>

<p>Consider the below NN architecture with 3 units in the input layer, 4 each in 2 hidden layers and 1 unit in the final layer (looks familiar 🤔- hmmm maybe of a binary classification task)</p>

<p><img src="https://user-images.githubusercontent.com/41947720/82881643-93e11c80-9f5d-11ea-9f0e-abe0d039ab66.png" alt="image" /></p>

<p>Can we represent the final output in a single line as a function of the input? (Hint - The diagram has weight matrices). The answer is yes. At each layer if we apply the formula shown above and combine all the three then we are done. Seems easy, isn’t it? But how is this going to help? Well, this representation comes handy when we are calculating gradients of the loss function with respect to the network parameters during backpropagation, which we will look at next.</p>

<p><img src="https://user-images.githubusercontent.com/41947720/82882732-1b7b5b00-9f5f-11ea-9873-a1df4a649dce.png" alt="image" /></p>

<p>Also, the concepts of basis, eigen-values, eigen-vectors, singular-value-decomposition are very crucial (Ex: they form the pillars of PCA (principal component analysis) which is a very important concept in Machine Learning (we won’t be discussing it here)). Having seen this let’s move on to the next topic i.e. Multivariate Calculus.</p>

<h2 id="multivariate-calculus">Multivariate Calculus</h2>

<p>Wikipedia defines Calculus as the mathematical study of continuous change and so it is. Most of us are familiar with the concepts of integration and differentiation in calculus but what role do they have to play here? As said, we can view ML models as a computational box where the inputs is undergoing changes in some stages and finally changing to the output (a complicated way of saying output is some function of the input 😉). Now, in the training process our goal is to reduce the loss (or to optimize the model on the training data). This is where the theory of continuous change comes.</p>

<p>For reducing the loss function we have to tweak the weights and biases (collectively the parameters of the model), more specifically we have to move “opposite to the direction of the gradient”.</p>

<p><img src="https://user-images.githubusercontent.com/41947720/82884842-f20ffe80-9f61-11ea-85b5-59f4fcabe909.png" alt="image" /></p>

<p>Consider this graph (here error surface), let us assume the z-axis represents the error and the x and y axes represent the parameters of the model. Now for reducing the error (or loss), we have to move in the x-y plane in the direction opposite to the gradient of the loss function wrt the parameters x and y (note - I’m not discussing the proof here). This commonly involves <em>vectorial differentiation</em> and the <em>chain-rule</em> over the loss function to some kth layer. Thankfully, we don’t have to perform it ourselves ( we have Tensorflow and pytorch!). However, it is important to know about it.</p>

<p>The image below shows the chain rule of differentiation.</p>

<p><img src="https://user-images.githubusercontent.com/41947720/82885427-cd685680-9f62-11ea-9dc6-eb388720d19e.png" alt="image" /></p>

<p>Having a general idea of Calculus helps while carrying out research and building new models from scratch. Having said this, let’s move on to the final topic Probability and Statistics.</p>

<h2 id="probability-and-statistics">Probability and Statistics</h2>

<p><em>the bedrock of ML</em></p>

<p><img src="https://user-images.githubusercontent.com/41947720/82890331-9f3a4500-9f69-11ea-84ed-5d7ce9eab0d3.png" alt="image" /></p>

<p>Probability is the study of uncertainty. It is a science that quantifies the likely-hood of the occurrence of the events of interest in a given setting. But, how is it related to ML? Well, isn’t ML about developing predictive models from uncertain data? Here is where Probability comes in. Probability is used almost everywhere in ML from defining <a href="https://machinelearningmastery.com/cross-entropy-for-machine-learning/">cross-entropy</a> as the loss function of a classification task, <a href="https://en.wikipedia.org/wiki/Normal_distribution">sampling data from specific gaussian distributions</a>, usage in algorithms like <a href="https://en.wikipedia.org/wiki/Naive_Bayes_classifier">Naive Bayes</a> to study of <a href="https://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/">Bayesian Machine Learning</a> (a separate branch of ML based on Bayesian inferences). Having a clear understanding of Probability is a <em>must</em> if you want to excel in ML.</p>

<p><img src="https://user-images.githubusercontent.com/41947720/82890578-09eb8080-9f6a-11ea-92db-fad856eed3eb.png" alt="image" /></p>

<p><em>The formula above shows Kullback - Liebler Divergence to calculate the similarity between two probability distributions</em></p>

<p>Why is Statistics used along with Probability? Statistics is the study of data (includes its collection, organization and analysis). Mean, median, quartiles, variance, and standard deviation which are statistical topics are dealt with in the form of evaluation of expectation values of probability distribution functions along with their other properties.</p>

<p>Since we deal with huge data in ML models, the task of organizing them and preparing them to be fed to the model is dealt by statistics (Ex: We enforce batch normalization before feeding image data to deep CNNs (convolutional neural networks))</p>

<p><img src="https://user-images.githubusercontent.com/41947720/82890725-40290000-9f6a-11ea-8176-33e522c3abe4.png" alt="image" /></p>

<p><em>The above figure is of a common data distribution considered in ML (the gaussian distribution)</em></p>

<p>Prob-Stat is indeed the most important topic of maths used in ML.</p>

<h3 id="resources-for-learning">Resources for Learning</h3>

<ul>
  <li>Linear Algebra -
    <ul>
      <li><a href="https://www.khanacademy.org/math/linear-algebra">Khan Academy</a></li>
      <li><a href="https://www.youtube.com/watch?v=kjBOesZCoqc&amp;list=PL0-GT3co4r2y2YErbmuJw2L5tW4Ew2O5B">3 blue-1 brown</a></li>
    </ul>
  </li>
  <li>
    <p><a href="https://www.coursera.org/learn/multivariate-calculus-machine-learning">Calculus</a></p>
  </li>
  <li>Probability and Statistics
    <ul>
      <li><a href="https://www.khanacademy.org/math/statistics-probability">Khan Academy</a></li>
      <li><a href="https://machinelearningmastery.com/probability-for-machine-learning-7-day-mini-course/">Machine Learning Mastery Blog</a></li>
    </ul>
  </li>
</ul>

<h4 id="bonus">Bonus</h4>

<p><a href="https://mml-book.github.io/book/mml-book.pdf">For book lovers</a></p>

<p><a href="https://www.coursera.org/specializations/mathematics-machine-learning">A complete course</a></p>

<h2 id="conclusion">Conclusion</h2>

<p><img src="https://user-images.githubusercontent.com/41947720/82891460-67340180-9f6b-11ea-82bb-9960d7538913.png" alt="image" /></p>

<p>This post helps the reader to understand why Mathematics is used in ML and how exactly. The explanations provided are a motivation for further learning. I have also provided Resources for each topic discussed.</p>

<p>For more ML and DL content stay tuned!</p>]]></content><author><name>Nischal Ashok Kumar</name></author><category term="Machine Learning" /><category term="Mathematics" /><summary type="html"><![CDATA[]]></summary></entry></feed>