<?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 Nikhil Dharap on Medium]]></title>
        <description><![CDATA[Stories by Nikhil Dharap on Medium]]></description>
        <link>https://medium.com/@ndharap?source=rss-fdefd04bcc7a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wATMMlcXFJWFIVCIDdNKgQ.jpeg</url>
            <title>Stories by Nikhil Dharap on Medium</title>
            <link>https://medium.com/@ndharap?source=rss-fdefd04bcc7a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 03:00:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ndharap/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[Language Models are Open Knowledge Graphs .. but are hard to mine!]]></title>
            <link>https://medium.com/data-science/language-models-are-open-knowledge-graphs-but-are-hard-to-mine-13e128f3d64d?source=rss-fdefd04bcc7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/13e128f3d64d</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[knowledge-base]]></category>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[getting-started]]></category>
            <dc:creator><![CDATA[Nikhil Dharap]]></dc:creator>
            <pubDate>Sun, 17 Jan 2021 16:48:30 GMT</pubDate>
            <atom:updated>2021-02-01T15:54:13.930Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/getting-started">Getting Started</a></h4><h3>Language Models are Open Knowledge Graphs .. but are hard to mine!</h3><h4>Join me as I dive into the latest research paper on creating knowledge graphs using transformer based language models</h4><blockquote>In this article, we will explore the latest research paper on building knowledge graphs from text by leveraging transformer based language models. The paper we will look at is called “<a href="https://arxiv.org/pdf/2010.11967v1.pdf">Language Models are Open Knowledge Graphs</a>”, where the authors claim that the “paper shows how to construct knowledge graphs (KGs) from pre-trained language models (e.g., BERT, GPT-2/3), <strong>without human supervision</strong>.”</blockquote><blockquote>The last part, which claims to have removed humans from the process, got me really excited. Having said that, I have learnt to take such claims with a grain of salt. I decided to explore this method further by experimenting with various components of the pipeline proposed in the paper. The idea is to understand the impact of each step in the pipeline on a domain specific example, and gauge if there is any supervision needed by either domain experts or data scientists.</blockquote><p><strong>Note</strong>: I assume some familiarity with the concept of knowledge graphs and transformer based language models. Briefly, As stated <a href="https://www.ontotext.com/knowledgehub/fundamentals/what-is-a-knowledge-graph/">here</a> “The knowledge graph (KG) represents a collection of interlinked descriptions of entities — real-world objects and events, or abstract concepts (e.g., documents)”. It allows us to model the real world into a graph, which can then be reasoned over to assert facts about the world. To learn more about transformer based models, refer to Jay Alammar’s post <a href="http://jalammar.github.io/illustrated-transformer/">here</a> and <a href="http://jalammar.github.io/illustrated-bert/">here</a> . You can also refer to my post “<a href="https://towardsdatascience.com/beyond-classification-with-transformers-and-hugging-face-d38c75f574fb">Beyond Classification With Transformers and Hugging Face</a>”, where I dive into these models, especially the attention mechanisms, which is where most of the “knowledge” is stored.</p><p><strong><em>Without further ado, let’s dive in! :)</em></strong></p><p>Most of the leading companies have begun using Knowledge Graphs (KG) to organize, manage and expand knowledge about their businesses. While most businesses get quite far with populating KGs with instances from various structured data sources, they struggle with doing the same from unstructured sources like text. Extracting and building knowledge from text using Machine Learning (ML) &amp; Natural Language Processing (NLP) based techniques has been an area of focus for many leading universities and researchers. Let’s begin by looking at the approach, generally followed by most researchers, from a bird’s-eye view below. The process flow is pretty standard across the industry and you can find many publications and talks, but I found one talk (slightly dated, but very simple and concise) here : <a href="https://youtu.be/CBvE3BNErgE">Talk</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AwICcxF-RRcDulp-Pnimww.png" /><figcaption>Figure 1: A typical pipeline used to generate triplets for automatic knowledge graph population (mostly inferred from talks online , like this : <a href="https://youtu.be/CBvE3BNErgE">Link</a>)</figcaption></figure><p>As seen in the figure above, the process starts by parsing and enriching text with meta data like POS tags, named entities, dependency parse trees etc. The next step is to identify mentions in text (i.e. portions of the text) that can most likely qualify as entities in a knowledge graph. This is called Mention Detection. This is then passed through an entity linker, which finds the most likely candidate entities from the target KG, and then disambiguates by running logic on top (this could be ML, lookup dictionaries, string matching etc.), to map each mention to a particular node in the target KG. The final step is to come up with carefully designed linguistic features based on enrichments done in step 1 and entities using techniques from ML, first order logic or raw rules, to come up with most likely relations. The disambiguated entities and relations are then produced as output triplets (for e.g. subject, predicate, and object) to link into a graph.</p><blockquote>The biggest pain point with most of these approaches is the time and effort that they demand from technical specialists who could be data scientists, linguists and knowledge base developers. They need to work closely with domain experts, and come up with raw linguistic features based on enrichments, define domain specific dictionaries and/or first order logic, which can take weeks or months based on the size &amp; complexity, and may still end up missing information due to the amount of variation in the domain.</blockquote><h3>Leveraging Language Models for Knowledge Graph Construction</h3><p>More recently, the research community has started exploring how to leverage deep learning to build the linguistic features which were traditionally built by humans. Let’s look at one such paper -“<strong>Language Models are Open Knowledge Graphs” by Chenguang Wang, Xiao Liu, Dawn Song. </strong>There are a few resources that explain this paper in more detail online, but the paper is also an easy read. I will try to go through the paper high level, and then turn our focus on experimenting with their proposed pipeline.</p><p>The main idea behind this paper is to minimize the involvement of humans in the process of creating knowledge graphs from textual data. The authors hypothesize that transformer based models like BERT or GPT2 have the capacity to learn and store knowledge about the domain, which can be converted to a structured knowledge graph. They go on to test this on TAC Knowledge Base Population (KBP) dataset and Wikidata, and publish encouraging results on KG population using the proposed method.</p><p>The proposed approach has two steps <strong>Match &amp; Map (MaMa)</strong>. Let’s look at how these modify the pipeline we discussed above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IOYqDFTQmPdc3clRagVPhA.png" /><figcaption>Figure 2: High level “MaMa” process flow proposed in the paper “Language Models are Open Knowledge Graphs”</figcaption></figure><p>The place where this approach differs from the previous methods is the <strong>use of attention mechanisms</strong> <strong>to infer candidate triplets in text</strong>. The attention weights, which the pre-trained transformer-based models have learnt during training, provide us with insights into the relationship between various terms in text. These weights, applied to anchor terms (noun chunks) from a standard library like <a href="https://spacy.io/">spaCy</a>, provide possible candidates facts (head, relation, tail), which can then be disambiguated using an off-the-shelf entity linker like <a href="https://github.com/informagi/REL">REL</a>.</p><p>Following is a diagram taken directly from the paper. It shows how the match process works by running a beam search to find triples with highest aggregate score.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kl2ASp__Tcq3Twizpx83cw.png" /><figcaption>Source: <a href="https://arxiv.org/pdf/2010.11967.pdf">https://arxiv.org/pdf/2010.11967.pdf</a></figcaption></figure><p>Let’s take this a step further and create a granular version of the proposed pipeline based on the code provided <a href="https://github.com/theblackcat102/language-models-are-knowledge-graphs-pytorch">here</a> (<em>the paper does not provide some of the smaller details</em>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8o7EA5r_mfMkWrY1hVlwmQ.png" /><figcaption>Figure 3: Detailed flow diagram that shows steps in the pipeline at a lower granularity</figcaption></figure><p>As we see from the flow above, the pipeline involves a lot more than just running the sentences through an LM. While an LM may help us generate candidate facts, it is equally important to tune the other parts of the pipeline. All the other pieces of the pipeline try to leverage pre-trained models from libraries like <a href="https://spacy.io/">spaCy</a>, <a href="https://github.com/informagi/REL">REL</a> and <a href="https://github.com/flairNLP/flair">Flair</a>.</p><h3>The Experiment</h3><p>Now that we know what the authors of the paper are attempting to achieve, let’s start experimenting with their pipeline, and see if we can achieve the intended result on a couple of small samples.</p><p>We will pick one example that has an overlap between the general domain and healthcare:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KaTPk_ADzDetGDeps9paoQ.png" /><figcaption>Source: <a href="https://www.survivornet.com/articles/did-you-know-robert-de-niro-is-15-years-cancer-free-now-hes-starring-in-the-irishman-nominated-for-2-emmys/">https://www.survivornet.com/articles/did-you-know-robert-de-niro-is-15-years-cancer-free-now-hes-starring-in-the-irishman-nominated-for-2-emmys/</a></figcaption></figure><p>The second example is healthcare specific:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C4sB0R_CNxVqTDXiE9z-Dg.png" /><figcaption>Source: <a href="https://www.dph.illinois.gov/topics-services/diseases-and-conditions/diseases-a-z-list/conjunctivitis">https://www.dph.illinois.gov/topics-services/diseases-and-conditions/diseases-a-z-list/conjunctivitis</a></figcaption></figure><p>We will start the experiment by using their default implementation, and then move onto tweaking different steps in the pipeline, visualizing the output as we proceed.</p><blockquote>The original code from the paper can be found here: <a href="https://github.com/theblackcat102/language-models-are-knowledge-graphs-pytorch">Original Code</a></blockquote><blockquote>I forked the repo and made some changes, namely — wrapper to run and visualize the output using dash, support to run scispaCy Named Entity Recognizer (NER) and Entity Linker, and ability to run different language models supported through the Hugging face transformers library. Here is the link to my <a href="https://github.com/nidharap/language-models-are-knowledge-graphs-pytorch/tree/feature/UseNERWithNouns">forked repo</a> (still in a branch as I add more stuff to experiment, and eventually will be merged into main)</blockquote><h3>1. Out-of-the-box:</h3><ul><li>Noun Chunks for anchor terms found using en_core_web_md model from spaCy</li><li>bert-large-cased model for Language Model</li><li>REL library for entity linking to wikidata 2019 knowledge graph</li><li>Sample sentence: <em>One thing many people don’t know about actor Robert De Niro — known for his many infamous tough guy roles in films such as “Goodfellas” and “Taxi Driver” — is that he is a 15-year cancer survivor. De Niro was diagnosed with prostate cancer when he was 60 years old in 2003. But thanks to regular cancer screening which led to his doctors catching the disease early, the actor was treated swiftly — and was able to continue his prolific acting career.</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SxczDWCemJn-B2rflU1aeg.png" /><figcaption>Figure 4: Default configuration from the original repo run on the first sentence (related to Robert Di Nero)</figcaption></figure><p>As you can see, it found only 1 triplet and was able to link it to wikipedia entities:</p><p><strong>head</strong>: “Robert_De_Niro”, <strong>relation</strong>: “diagnose”, <strong>tail</strong>: “Prostate_cancer”, <strong>confidence</strong>: 0.16</p><p>Note - you can just prefix the entity with <a href="https://en.wikipedia.org/wiki/Robert_De_Niro"><strong>https://en.wikipedia.org/wiki</strong></a><strong>/</strong> to explore the wikipedia page for that entity. For example: <a href="https://en.wikipedia.org/wiki/Prostate_cancer"><strong>https://en.wikipedia.org/wiki/Prostate_cancer</strong></a></p><h3>2. Leverage Named Entities in addition to Noun Chunks to identify anchor text (Step 3 in Figure 3)</h3><p>The authors use Noun chunks from spaCy to identify the anchor terms, which are then used to find triplets. We saw that the out-of-the-box implementation generated only one triplet. Most of the prior research uses named entities in this step (<em>see step 1 in Figure 1 that talks about the overall approach</em>), so let’s also use a Named Entity Recognizer (NER) to aid the process. Let’s leverage spaCy to also provide us with Named Entities, in addition to the Noun Chunks (<em>we remove any overlapping portions</em>). Let’s look at what gets generated for the same sentence:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vd4S2sBHZMFUU-uiwhvlDQ.png" /><figcaption>Figure 5: Adding Named Entities from the en_core_web_md model enables us to use the same Language Model (bert-large-cased) to generate a lot more triplets</figcaption></figure><p>As we see, there is a considerable impact of using Named Entities, as it was able to generate more triplets.</p><p><em>Note: You can also see that the entity linker (REL) does the best it can to identify entities for various mentions, and the fact that we have more mentions than needed can cause noise. For instance we have “</em><strong><em>many people</em></strong><em>” as a mention, which was disambiguated to </em><strong><em>“</em></strong><a href="https://en.wikipedia.org/wiki/Unforgettable_(Nat_King_Cole_song)"><strong><em>Unforgettable_(Nat_King_Cole_song)</em></strong></a><strong><em>”, </em></strong><em>“</em><strong><em>60 years old</em></strong><em>” was disambiguated to “</em><a href="https://en.wikipedia.org/wiki/Lettrism"><strong><em>Lettrism</em></strong></a><em>”. While we have not made an explicit effort to filter out specific entity types from spaCy here, we can do that based on use case requirements, which should remove many of the unwanted mentions, and hence relations. These are typical cost-benefit trade-offs that a use case has to make.</em></p><p>Let’s now try using this on a domain specific example from healthcare:</p><p><em>Conjunctivitis is an inflammation of the thin, clear membrane (conjunctiva) that covers the white of the eye and the inside surface of the eyelids. Conjunctivitis, commonly known as “pink eye,” is most often caused by a virus but also can be caused by bacterial infection, allergies (e.g., cosmetics, pollen) and chemical irritation.</em></p><p>The default model en_core_web_md does not produce much this time, even after adding Named Entities to the process -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vuKHzT_tbpL3Sqm85g570g.png" /><figcaption>Figure 6: NER with the default SpaCy Model on a domain specific example from healthcare</figcaption></figure><p>Let’s switch to a domain specific pre-trained NER, that was trained on a healthcare dataset by allenai and released here : <a href="https://github.com/allenai/scispacy">scispaCy</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8gCtKSVCXlsdWRz89ndrOA.png" /><figcaption>Figure 7: NER from a domain specific model en_core_sci_lg that was downloaded from <a href="https://github.com/allenai/scispacy">scispaCy</a></figcaption></figure><p>As we see above, the domain specific NER generates more triplets. There are a few incorrect triplets that get extracted too, and a couple of reasons why this may happen -</p><ol><li>The threshold used to filter out triplets is low (default of 0.005), which brings back a lot more relations. We will look at the effect of threshold further down in the article.</li><li>The confidence in triplets (generated based on attentions) also depends on the type of LM used. This model was primarily trained on a general dataset like wikipedia (not healthcare specifically), and hence may not have seen these terms enough number of times.</li></ol><p>Switching to a different scispaCy Model to identify Named Entities gives us significantly different results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z_uHTwIydYUGv8qAD9NtBQ.png" /><figcaption>Figure 8: NER from a domain specific model en_ner_bc5cdr_md that was downloaded from <a href="https://github.com/allenai/scispacy">scispaCy</a></figcaption></figure><blockquote><strong>Observation</strong>: It is clear that the same Language Model produced many more triplets when we leveraged a relevant named entity model to pick the anchor terms instead of just the noun chunks or using the default NERs from SpaCy.<strong> This shows that it is not easy to just plug and play, and it is necessary for a data scientist/NLP expert to pick the right method upfront to identify anchor text, which may need some experimenting or training.</strong></blockquote><h3>3. Pick a relevant Entity Linker (Step 8 in Figure 3)</h3><p>Let’s run the domain specific example about Conjunctivitis through the default entity linker (REL). <a href="https://github.com/informagi/REL">REL</a> has an option to pick the wikipedia corpus year (I picked wiki_2019), which then maps the mentions to entities in the 2019 version of wikipedia. Let’s look at the output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MW-znQap8f-Zvm02Fd4nZQ.png" /><figcaption>Figure 9: REL entity linker that was trained to match entities in the wiki corpus. Here is the link to the tool — <a href="https://github.com/informagi/REL">https://github.com/informagi/REL</a></figcaption></figure><p>We see in the figure above that it does a decent job at resolving entities. This is because we picked an example that has well known concepts, which have some reference in the wikipedia KG. Let’s pick a complex sentence from the same domain -</p><pre>Phenylketonuria (PKU) and mild hyperphenylalaninemia (MHP) are allelic disorders caused by mutations in the gene encoding phenylalanine hydroxylase (PAH).</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rrL-11kPzjQR_iNMVyAmIQ.png" /><figcaption>Figure 10: A complex healthcare example run through bert-large-cased model, and en_core_sci_lg model from scispaCy and REL entity linker</figcaption></figure><p>The above graph was generated by passing the sentence through bert-large-cased model, en_core_sci_lg model from scispaCy for Named Entities, and REL entity linker. We can see that the entity linker does well on some entities, but fails on others. Entities like “Mutant_(Marvel_Comics)” or “National_Movement_Party” are clearly incorrect.</p><p>The graph below was generated using the same configuration except the scispaCy entity linker, which was built to identify concepts in the healthcare domain. The scispaCy entity linker also allows us to map the concepts to different knowledge graphs in the medical domain. I picked the <a href="https://www.nlm.nih.gov/research/umls/licensedcontent/umlsknowledgesources.html">UMLs</a> KG as the target. We can see that this entity linker did quite well in disambiguating the nodes. Here, again, tweaking the threshold can remove a number of incorrect triplets, which is discussed in the next section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CWs6ANisyiTbvTea2RbPLQ.png" /><figcaption>Figure 11: A complex healthcare example run through bert-large-cased model, and en_core_sci_lg model and entity linker both from scispaCy</figcaption></figure><blockquote><strong>Observation</strong>: Having access to a<strong> relevant entity linker</strong> can <strong>save a lot of time and effort</strong> by identifying the right entities in the target KG. It plays a key role in being able to extract as much automatically, leaving less work for humans that would otherwise need to correct entities and relations</blockquote><h3>4. Pick the right threshold to filter triplets (Step 7 in Figure 3) and a relevant Language Model (Step 2 in Figure 3)</h3><p>Finally, let’s investigate the impact of switching language models and the threshold used to filter out triplets. These two aspects are related because picking a language model will determine the average threshold that will work for the filtering process.</p><p>The paper provides some insights into the difference between using a BERT like model vs a GPT style model (auto-regressive in nature). They indicate that BERT-like models have better success at identifying relations because they are bidirectional in nature and see tokens in both directions while learning to predict masked tokens. This was consistent in my experiments and hence, I decided to focus on BERT based models for further analysis.</p><p>Let’s start with the same example that discusses Conjunctivitis:</p><p><em>Conjunctivitis is an inflammation of the thin, clear membrane (conjunctiva) that covers the white of the eye and the inside surface of the eyelids. Conjunctivitis, commonly known as “pink eye,” is most often caused by a virus but also can be caused by bacterial infection, allergies (e.g., cosmetics, pollen) and chemical irritation.</em></p><p>We will experiment with two transformer based models:</p><p>Healthcare domain specific language model from Hugging face (<a href="https://huggingface.co/bionlp/bluebert_pubmed_mimic_uncased_L-24_H-1024_A-16">Link</a>) : “‘<a href="https://huggingface.co/bionlp/bluebert_pubmed_mimic_uncased_L-24_H-1024_A-16">bionlp/bluebert_pubmed_mimic_uncased_L-24_H-1024_A-16</a>’’</p><p>Default model: bert-large-cased</p><p>We will also try three values for threshold: 0.005, 0.05 and 0.1</p><p>Each graph below is an output from one of the configuration as detailed in the description below it. You can also see the top portion of each Figure to see the other parameters used. The confidence values for each triplet is marked on the corresponding edge with the pattern &lt;relationName_confidenceScore&gt;:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bYGMWlgR7LX1rzRQ-MyR_w.png" /><figcaption>Figure 12 (above): <strong>model</strong>: bert-large-cased, <strong>threshold</strong>: 0.005 (default)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ffDQ2YlOHTbrttNgD0vRIQ.png" /><figcaption>Figure 13 (above): <strong>model</strong>: bionlp/bluebert_pubmed_mimic_uncased_L-24_H-1024_A-16, <strong>threshold</strong>: 0.005 (default)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x9qNxxi_nnJJr-QhxZxqUQ.png" /><figcaption>Figure 14 (above): <strong>model</strong>: bert-large-cased, <strong>threshold</strong>: 0.05</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hBAzK6IqEyRmcL2Fs7WJGA.png" /><figcaption>Figure 15 (above): <strong>model</strong>: bionlp/bluebert_pubmed_mimic_uncased_L-24_H-1024_A-16, <strong>threshold</strong>: 0.05</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G813Ba_kvz0j3phg-feEMQ.png" /><figcaption>Figure 16: (above): <strong>model</strong>: bionlp/bluebert_pubmed_mimic_uncased_L-24_H-1024_A-16, <strong>threshold</strong>: 0.1</figcaption></figure><blockquote><strong>Observation</strong>: The graphs are almost identical for the two models when the threshold is set to 0.005 (suggested by the authors). The difference starts showing when we move to a higher threshold of 0.05. The domain specific model (bionlp/bluebert_pubmed_mimic_uncased_L-24_H-1024_A-16) displayed more confidence overall in its triplets when the threshold was moved from 0.005 to 0.05<em>. </em>Initially<em>, </em>I had assumed that the threshold would just remove some existing triplets and keep the rest as is, but that was a wrong assumption. Most of the triplets had updated scores, higher than earlier, when the threshold was changed from 0.005 to 0.05. This would mean that the beam search, which assigns scores to each triplet, summed up more values for each triplet due to lesser number of candidates.</blockquote><blockquote>Overall, there is a tradeoff between threshold and number of triplets, and it is up to the NLP expert to pick the right threshold, which does change the extracted triplets significantly.</blockquote><h3>Conclusion</h3><p>It is encouraging to see that language models can be used to extract candidate facts from text, but as we observed in the experiments above, it is equally important for the data scientist/NLP expert to get the rest of the pipeline tuned to the use case.</p><p>Getting the right “knowledge” out depends heavily on a lot more factors beyond plugging in a pre-trained LM like:</p><ol><li>Identifying the right anchor terms (noun chunks ,named entities etc.)</li><li>Configuring the relevant relation types (<em>this aspect was not discussed in the article, but the authors also set constraints on what relations are valid based on predefined dictionaries</em>)</li><li>Having access to a relevant pre-trained entity linkers</li><li>Tuning the right thresholds for triplets</li></ol><h3>References</h3><ul><li>Original Paper: <a href="https://arxiv.org/pdf/2010.11967.pdf">Link</a></li><li>Original Code: <a href="https://github.com/theblackcat102/language-models-are-knowledge-graphs-pytorch">Link</a></li><li>Transformer Models from Hugging Face: <a href="https://huggingface.co/">Link</a></li><li>REL Entity Linker Original Paper: <a href="https://arxiv.org/pdf/2006.01969.pdf">Link</a></li><li>REL Entity Linker Github: <a href="https://github.com/informagi/REL">Link</a></li><li>scispaCy: <a href="https://github.com/allenai/scispacy">Link</a></li><li>scispaCy for Bio-medical Named Entity Recognition(NER): <a href="https://medium.com/@maheshdmahi/scispacy-for-bio-medical-named-entity-recognition-ner-63ed548f1df0#id_token=eyJhbGciOiJSUzI1NiIsImtpZCI6IjI2MTI5YmE1NDNjNTZlOWZiZDUzZGZkY2I3Nzg5ZjhiZjhmMWExYTEiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20iLCJuYmYiOjE2MDk3Mzc0OTksImF1ZCI6IjIxNjI5NjAzNTgzNC1rMWs2cWUwNjBzMnRwMmEyamFtNGxqZGNtczAwc3R0Zy5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbSIsInN1YiI6IjExNjQ0OTg2NDgzNjgwNTg5MTM1NiIsImVtYWlsIjoibmRoYXJhcEBnbWFpbC5jb20iLCJlbWFpbF92ZXJpZmllZCI6dHJ1ZSwiYXpwIjoiMjE2Mjk2MDM1ODM0LWsxazZxZTA2MHMydHAyYTJqYW00bGpkY21zMDBzdHRnLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwibmFtZSI6Im5pa2hpbCBkaGFyYXAiLCJwaWN0dXJlIjoiaHR0cHM6Ly9saDMuZ29vZ2xldXNlcmNvbnRlbnQuY29tL2EtL0FPaDE0R2o5REM1MXdhRDdvZENqZ091YUZHbzRjOVZRMWlSMG53ZmRQTmFqWVE9czk2LWMiLCJnaXZlbl9uYW1lIjoibmlraGlsIiwiZmFtaWx5X25hbWUiOiJkaGFyYXAiLCJpYXQiOjE2MDk3Mzc3OTksImV4cCI6MTYwOTc0MTM5OSwianRpIjoiN2JlZjcxYThmMjBjZWVhMzUzNjRmYmVhMDAwNzg0NGJmM2U5ZGQwOCJ9.fQgklLhQ_6o5jiUO20nnBrMZ9a0a58dN0P_g42ZJVwot6qxSd9RGN-M1FDbkdC9jABxYIDbfJbFsW--a2FD-BN5ZrAFdQBDIzHScaXM6bVHlC86Nw4zfhZ_y8RFgMPgqZlxHJdh4tDQpDwseOgDVwxpY9oMd4JWIWYIDNiEwU3eqhe7s8YxfK56hpzwg-TlqGHldKRMyS3pdWfXE_zc0k_G1MvyDSxE9KKmS7MUKG1bEyz2NKGtdpBmPFZBWH661ZNnBt4u-gjqjlus1Ddnw20izWIg3FNndlCKFIK_qiSzG_XXzHQc3kcaXH_ETKWdKPyO7SLmkp03eqesjzpzAhw">Link</a></li><li>Dash from Plotly: <a href="https://plotly.com/dash/">Link</a></li><li>Dash + Plotly for network visualization : <a href="https://towardsdatascience.com/python-interactive-network-visualization-using-networkx-plotly-and-dash-e44749161ed7">Link</a></li><li>Data from:</li></ul><ul><li><a href="https://www.ijddr.in/drug-development/diabetes-mechanism-pathophysiology-and-managementa-review.php?aid=6713">Diabetes: Mechanism, Pathophysiology and Management-A Review</a></li><li><a href="https://www.dph.illinois.gov/topics-services/diseases-and-conditions/diseases-a-z-list/conjunctivitis">Conjunctivitis</a></li><li><a href="https://www.nlm.nih.gov/research/umls/licensedcontent/umlsknowledgesources.html">UMLS Knowledge Sources: File Downloads</a></li></ul><pre><a href="https://www.kaggle.com/tboyle10/medicaltranscriptions">https://www.kaggle.com/tboyle10/medicaltranscriptions</a></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13e128f3d64d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/language-models-are-open-knowledge-graphs-but-are-hard-to-mine-13e128f3d64d">Language Models are Open Knowledge Graphs .. but are hard to mine!</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond Classification With Transformers and Hugging Face]]></title>
            <link>https://medium.com/data-science/beyond-classification-with-transformers-and-hugging-face-d38c75f574fb?source=rss-fdefd04bcc7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d38c75f574fb</guid>
            <category><![CDATA[attention]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[bert]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[sentence-similarity]]></category>
            <dc:creator><![CDATA[Nikhil Dharap]]></dc:creator>
            <pubDate>Mon, 10 Aug 2020 23:55:34 GMT</pubDate>
            <atom:updated>2020-08-12T01:29:47.137Z</atom:updated>
            <content:encoded><![CDATA[<h4>Go hands-on with Exploratory Model Analysis (EMA) on Transformers architectures, zooming into attentions, embeddings, and semi-supervised learning.</h4><blockquote>In this post, I plan to explore aspects of cutting edge architectures in NLP like BERT/Transformers. I assume that the readers are familiar with the Transformer architectures. To learn more about these, refer to Jay Alammar’s post <a href="http://jalammar.github.io/illustrated-transformer/">here</a> and <a href="http://jalammar.github.io/illustrated-bert/">here</a> . I am also going to explore a couple of BERT variations like BERT-base and RoBERTa-base models, but these techniques can be very easily extended to more recent architectures, thanks to Hugging Face!</blockquote><p>As I started diving into the world of Transformers, and eventually into BERT and its siblings, a common theme that I came across was the Hugging Face library (<a href="https://huggingface.co/transformers/">link</a>). It reminds me of scikit-learn, which provides practitioners with easy access to almost every algorithm, and with a consistent interface. The Hugging Face library has accomplished the same kind of consistent and easy-to-use interface, but this time with deep learning based algorithms/architectures in the NLP world. We will dig into the architectures with the help of these interfaces provided by the this library.</p><h3>Exploratory Model Analysis (EMA)</h3><p>One of the main components of any Machine Learning (ML) projects is Exploratory Data Analysis (EDA). Every ML project I have been part of in the past years has started with me and my team doing EDA, iteratively, which helped understand and formulate a concrete problem statement. Figure 1 below demonstrates the typical ML process with an iterative EDA phase, which aims at answering questions about the data to help make decisions, typically about methods to leverage the data to solve specific business problems (<em>say via modeling</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5gdZT23y6uvybzThonQF6w.png" /><figcaption>Figure 1: A typical ML flow with the Exploratory Data Analysis (EDA)</figcaption></figure><p>With the advent of Deep Learning (DL), especially with the option of transfer-learning, the exploration phase now extends beyond looking at the data. It also entails another cycle of exploration for models, let’s call that <strong>EMA</strong> <strong>(Exploratory Model Analysis)</strong>, which involves understanding the model architectures, their pre-training process, the data and assumptions that went into the pre-training, the architecture’s limitations (<em>e.g. input size, model bias, types of problems they cannot solve</em>), and the extent to which they can be fine-tuned for a downstream task. In other words, <em>analyze</em> <em>where do they lie in the spectrum of re-training, few-shots fine-tuning to zero-shot (as they say in the GPT-3 world)</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7FBQf0nDaqVbfrjBSYZciw.png" /><figcaption>Figure 2: EDA + EMA: A Typical Deep Learning flow with both EDA (Exploratory Data Analysis) and EMA (Exploratory Model Analysis) .. or should we just call it EDMA? :)</figcaption></figure><p>In this article, I would like to focus more on EMA on BERT (and the likes), to understand what can it provide beyond fine-tuning for classification or Q&amp;A. As I stated earlier, the Hugging Face library can provide us with the tools necessary to peek into the model, and explore various aspects of the model. More specifically, I would like to use the library to answer the following questions -</p><ol><li>How can I peek into the pre-trained model architecture and attempt to interpret the model results given the weights? <em>If you have heard of attention weights and how they could be used to interpret these models, we will explore how to access them using the Hugging Face library, and also visualize them.</em></li><li>How can I access outputs from various layers of BERT like models? What quality of output can I expect from these models, if I had to go completely unsupervised beyond? We will extract word and sentence vectors, and visualize them to analyze similarity. Further, we will examine the impact on quality of these vectors and metrics when we fine-tuning these models on a dataset from a completely different domain. To put it simply<em>, if we did not have domain specific datasets to fine-tune, how do we move forward?!</em></li></ol><p>These questions spawn from two pain points, <strong>limited availability of labelled data, and interpretability</strong>. Most of real world projects I have worked on, unlike Kaggle competitions, do not give us a nice labelled dataset, and the challenge is to justify the cost of creating labelled data. The second challenge, in some those projects, is also the ability to provide explanation of the model behavior, to hedge some flavor of risk.</p><p><strong><em>Without further ado, let’s dive in! :)</em></strong></p><h3>Easy access to Attention weights: <em>a step towards interpretation</em></h3><p>All the transformer based architectures today are based on attention mechanisms. I found that understanding the basics of how attention works helped me explore how that could be used as a tool for interpretation. I plan to describe the layers at a high level in this post, and focus more on how to extract them using the Transformers library from Hugging Face. If you need to understand the concept of attention in depth, I would suggest you go through Jay Alammar’s blog (<em>link provided earlier</em>) or watch this playlist by Chris McCormick and Nick Ryan <a href="https://www.youtube.com/watch?v=FKlPCK1uFrc&amp;list=PLam9sigHPGwOBuH4_4fr-XvDbe5uneaf6">here</a>.</p><p>The Hugging Face library provides us with a way access the attention values across all attention heads in all hidden layers. In the BERT base model, we have 12 hidden layers, each with 12 attention heads. Each attention head has an attention weight matrix of size NxN (N is number of tokens from the tokenization process). In other words, we have a total of 144 matrices (12x12), each of size NxN. The final embedding size of each token at every layer input or output is 768 <em>(which comes from 64 dimensional vectors from each attention head i.e. 64x12 = 768)</em>. <em>This will be clear as you move to figure 4 below.</em></p><p>Figure 3 provides the architecture for an encoder layer. Figure 4 below drills into the <strong>Attention</strong> block from Figure 3, and provides a simplified, high-level flow of one sentence through one attention layer of the BERT base model (<em>ignoring the batch_size for simplicity</em>). These diagrams hopefully provides clarity on what matrix will be returned when you turn the output_attentions flag to true via the library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LMk1R2-977MPwFcWfVZSQw.png" /><figcaption>Figure 3: A simplified diagram of the encoder stack. As you can see, we get a vector for each token after each encoder layer. The next diagram (Fig 4 below) drills into the attention block in one of these encoder blocks</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cm3fTRbOIrThaa6Tk3lUuQ.png" /><figcaption>Figure 4: A simplified, high-level flow of one sentence (batch dim ignored for simplicity) through one self attention layer of the BERT base model. The input matrix, Nx768 (N rows, one for each token, each embedded into 768 dimensions) flows through the attention layer (the box in the center). When we set output_attention=True in the BertConfig, it returns the matrix ‘A’ for each for attention head.</figcaption></figure><p><strong><em>Note</em></strong><em>: I found tools </em><a href="https://arxiv.org/pdf/1906.05714.pdf"><em>here</em></a><em> and </em><a href="https://github.com/tensorflow/tensor2tensor"><em>here</em></a><em>, which enable us to visualize attentions. These tools are either deprecated or do not implement all the latest architectures. Further, instead of leveraging the well maintained APIs like Hugging Face, one of them re-implements the architectures within, which hampers the chance to run things for newer architectures.</em></p><p>Let’s quickly walkthrough the code (<em>the full notebook can be found </em><a href="https://github.com/nidharap/Notebooks/blob/master/Attentions_in_BERT.ipynb"><em>here</em></a>). <strong>All sthe code here, except fine-tuning, can be run without a GPU</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/160e6c7ffabf0598eda60b12983e6292/href">https://medium.com/media/160e6c7ffabf0598eda60b12983e6292/href</a></iframe><p>The code above creates a Bert config with <strong>output_attentions=True</strong>, and uses this config to initialize the Bert base model. We put the model into eval mode since we just care about doing a forward pass through the architecture for this task. The code then goes onto tokenize and do a forward pass. The shape of the output is based on the config passed as described the documentation <a href="https://huggingface.co/transformers/model_doc/bert.html#bertmodel">here</a>. The first two items are last_hidden_state for the last layers and the pooled_output that can be used for fine tuning. The next input is what we are interested in, which is the attentions. As you can see from the last three statements, we can reach any layer, and any attention head, each of which will give us a NxN matrix we are interested in.</p><p>We can quickly plot a heatmap for any of the 144 matrices like below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/967660549e5751b6da0b60bb4a5ac24b/href">https://medium.com/media/967660549e5751b6da0b60bb4a5ac24b/href</a></iframe><p>The code above has two simple functions:</p><p><em>“get_attentions” navigates to the particular layer and attention head, and grabs the NxN matrix to be visualized</em></p><p><em>“plt_attentions” plots the matrix passed as a heat map</em></p><p>As part of my EDA in the full notebook <a href="https://github.com/nidharap/Notebooks/blob/master/Attentions_in_BERT.ipynb">here</a>, I plotted all the 144 heatmaps as a grid, and skimmed through them to spot some that had a good variation of attention weights. One of them in particular in Figure 3 below shows the relation between the words ‘it’ and ‘animal’ in the sentence “The animal didn’t cross the street because it was too tired”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A4YjTu9WgbQx3fiC69kxvQ.png" /><figcaption>Figure 5: The attention heatmap for the sentence “The animal didn’t cross the street because it was too tired” from layer 9 and attention head 10. We can see that the the word “it” has a large weight for “animal”.</figcaption></figure><p>As you can see, with some basic understanding of architecture, the transformers library by Hugging Face makes it extremely easy to pull out raw weights from any attention head. Now that we discussed how to pull out raw weights, let’s talk a bit about whether we should use them directly to interpret what the model has learnt. A recent paper “Quantifying Attention Flow in Transformers” discussed exactly this aspect. They state <em>“across layers of the Transformer, information originating from different tokens gets increasingly mixed”</em></p><p>This means reading too much into these weights to interpret how the model deconstructs the input text may not be very useful. They go on to device a strategy to help interpret the impact of inputs on outputs. I won’t dive into the full paper here, but in short, they discuss building a Directed Acyclic Graph (DAG) on top of the architecture, which will help track paths and information flow between pairs of inputs and the hidden tokens. They discuss two approaches “attention rollout” and “attention flow”, that could be used to interpret attention weights as the relative relevance of the input tokens. In simple terms, instead of looking at only the raw attentions in a particular layer, you should consider a weighted flow of information all the way from the input embedding to the particular hidden output. If you are interested to know more, you can also refer to this <a href="https://samiraabnar.github.io/articles/2020-04/attention_flow">article</a>, that explains the paper with examples.</p><p><strong>In summary, to interpret the effect of specific inputs, instead of looking at only the raw attentions independently in each layer, we should take it a step further by using them to track the contribution all the way from the input embedding to specific outputs.</strong></p><h3>Access to word and sentence vectors: paths to similarity (and clustering, classification etc.)</h3><p>As we discussed, it is quite easy to access the attention layers and the corresponding weights. The Hugging Face library also provides us with easy access to outputs from each layer. This allows us to generate word vectors, and potentially sentence vectors.</p><p><strong>Word Vectors</strong></p><p>Figure 6 below shows a few different ways we can extract <strong>word level vectors</strong>. We could average/sum/concat the last few layers to get a vector. The hypothesis would be that the initial layers (closer to the inputs) would learn low level features (<em>like in a CNN</em>), and the final few layers (closer to the output) would have a much richer representation of the words. We could also just extract the last or the second to last layer as a word/token vector. There is no consensus on what one should use, and it would really depend on the requirement of the downstream task, <em>and it may not even matter so much if the task we are trying to run downstream is simple enough.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6mZjFFuizkjP4TpZtsWbJA.png" /><figcaption><em>Figure 6 Word Vectors:</em> Ways we can extract vectors for each token. On the left, it shows how we could either average, sum or concatenate over last 4 layers to get one vector for token-1. On the right, it shows how we could access a vector for Token-N from last or second last layer.</figcaption></figure><p><strong>Word Similarity</strong></p><p>Once we have word vectors, we are ready to use them in a downstream task like similarity. We can either directly visualize them using dimensionality reduction techniques like PCA or tSNE. Instead, I generally try to find distances between these vectors first in the higher dimension, and then use techniques like Multi Dimensional Scaling (MDS; <em>ref </em><a href="https://en.wikipedia.org/wiki/Multidimensional_scaling"><em>Link</em></a>) to visualize the distance matrix. Figure 7 below summarizes this approach (<em>we can do this for sentences as well, as long as we plan to access to sentence vectors directly, more on this later in the post</em>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wtAWj19pdZDXLt2S-n3BjQ.png" /><figcaption>Figure 7: Flow of how to visualize word vectors using a cosine distance + MDS (Multi dimensional Scaling) for 4 words</figcaption></figure><p><strong>Implementation: Word Similarity</strong></p><p>Let’s start looking through some code that implements the above flow. <em>The full colab notebook can be found </em><a href="https://github.com/nidharap/Notebooks/blob/master/Word_Embeddings_BERT.ipynb"><em>here</em></a></p><p>We will follow the same process as we used to initialize and visualize attention weights, except this time we use “<strong>output_hidden_states=True” </strong>while initializing the model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/149db2750b8c3a9b83650afbacd0a1e6/href">https://medium.com/media/149db2750b8c3a9b83650afbacd0a1e6/href</a></iframe><p>We also switch to encode_plus instead of encode, which will help us add CLS/SEP/PAD tokens, with a lot less effort. We build some additional logic around it to get attention masks that mask the PADs and also the CLS/SEPs.<em> Notice the return values in the below function</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d81eb53a602e4ba183005feec5d703b1/href">https://medium.com/media/d81eb53a602e4ba183005feec5d703b1/href</a></iframe><p>Let’s define the model and call it on the sample sentences.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b0028a4e3ed397c42b98322200eaacc/href">https://medium.com/media/0b0028a4e3ed397c42b98322200eaacc/href</a></iframe><p>Let’s define few helper functions:</p><ul><li><strong>get_vector</strong>: Extract vectors as needed <em>(concat/sum across multiple layers as discussed in the diagrams above etc.)</em></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c83cd0442057801b796783f4762f00f/href">https://medium.com/media/4c83cd0442057801b796783f4762f00f/href</a></iframe><ul><li><strong>plt_dists</strong>: Plot distance matrix passed. This calculates an MDS plot over a distance matrix passed.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f618119308fc462ac2c6285ac36e8c8/href">https://medium.com/media/5f618119308fc462ac2c6285ac36e8c8/href</a></iframe><ul><li><strong>eval_vecs</strong>: Tie get_vector and plt_dists together to get word vectors for sentences</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bebb3ccbfe90f9cb47f460f710bd64d9/href">https://medium.com/media/bebb3ccbfe90f9cb47f460f710bd64d9/href</a></iframe><p>Thats it! We are now ready to visualize these vectors in different configurations. Let’s look at one of them, concatenating the word vectors from the last 4 layers, and visualizing. We pass two sentences</p><pre>texts = [<br>&quot;Joe took Alexandria out on a date.&quot;,<br>&quot;What is your date of birth?&quot;,<br>]</pre><p>And then call the function to plot the similarity</p><pre>MODE = &#39;concat&#39;</pre><pre>eval_vecs(hidden_states, tokenized_sents, mode=&#39;concat&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rwpy3Kh8Hehx9zrcrb2zlQ.png" /><figcaption>Figure 8: As you can see, date_0 and date_1 are different vectors, and are closer to other words in the respective sentence. This allows us to now use them based on the sentence they occur in (i.e. “contextualized”)</figcaption></figure><p><strong>Sentence Vectors</strong></p><p>The encoder based models provide us with a couple of options to get sentence vectors from the architecture. Figure 9 shows us these options:</p><ol><li>Sentence vectors could be extracted using the last layer (or averaged over last n layers) for the CLS token. I tried extracting and visualizing sentence similarity based on the CLS token, but it did not give me good results.</li></ol><blockquote><em>A quick note from the authors of BERT: This output is usually not a good summary of the semantic content of the input (</em><a href="https://huggingface.co/transformers/model_doc/bert.html#bertmodel"><em>source</em></a><em>).</em></blockquote><p>2. Average token vectors across the sentence. The token vectors themselves, as we discussed above, could come from concatenating/averaging over last N-layers or directly from the Nth layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WdfkG-9gSgPLSeVs4VirMw.png" /><figcaption><em>Figure 9: Sentence vectors could be extracted using the last layer CLS token directly OR could be averaged over all the tokens in the sentence, which in turn could come from the last layer, the second last layer or averaged over a few layers as we saw in Figure 6.</em></figcaption></figure><p><strong>Sentence Similarity</strong></p><p>Similarity of two sentences is very subjective. Two sentences could be very similar in one context, and could be treated as opposites in other contexts. For example, two sentences could be called similar because they are talking about certain a topic, and could be discussing both positive as well as negative aspects of the topic. Those sentences could be considered similar because they are talking about a common topic, but would be considered opposites, if the focus is polarity of the sentence. Most of these architectures are trained on an independent objectives like Masked Language Model(MLM) and Next Sentence Prediction (NSP), and are trained on large, varied datasets. What we get out-of-the-box in terms of similarity, may or may not be relevant, based on task at hand.</p><p>Irrespective, it is important to look at our options of understanding similarity. Figure 11 below summarizes our options with sentence similarity in a flow diagram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JNc9M-8J88SYCunIxAaK-w.png" /><figcaption>Figure 11: Different ways of calculating Sentence Similarity using BERT-like models</figcaption></figure><p>Option #1 and Option #2 above extract and try to create sentence vectors, which can then use the same pipeline we built for word vector similarity.</p><p>Option #3 tries to compute similarity between two sentences directly from word vectors, instead of attempting to create a sentence vectors explicitly. This uses a special metric called Word Movers Distance (WMD).</p><figure><img alt="You can read the original paper for WMD here, but in short, it is based on EMD (Earth movers distance) and tries to move the" src="https://cdn-images-1.medium.com/max/974/1*zNfH-5auk-9wQtkOsV4-tA.png" /><figcaption>Figure 10: WMD calculation: How the sentence on the left is converted “moved” to the sentence on the right</figcaption></figure><p>You can read the original paper for WMD <a href="http://proceedings.mlr.press/v37/kusnerb15.pdf">here</a>, but in short, it is based on EMD (Earth Movers Distance) and tries to move the words from one sentence to other using the word vectors. An example directly from the paper is show in Figure 10. There is a nice implementation of this <a href="https://github.com/src-d/wmd-relax">here</a>, and an awesome explanation <a href="https://stats.stackexchange.com/questions/303050/word-movers-distance-calculation-between-word-pairs-of-two-documents">here</a></p><p><strong>Implementation: Sentence Similarity</strong></p><p>The code to run through sentence similarity options is available as a colab notebook here <a href="https://github.com/nidharap/Notebooks/blob/master/Sentence_Embeddings_RoBERTa.ipynb"><em>here</em></a></p><p>Most of the code is very similar to the word embeddings piece we discussed earlier, except calculating the word movers distance. The class below calculates the word movers distance using <a href="https://github.com/src-d/wmd-relax">WMD-relax</a> library. it needs access to an embedding lookup, that yields a vector when a word is passed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a81fbf418260f4d568fc539d22785188/href">https://medium.com/media/a81fbf418260f4d568fc539d22785188/href</a></iframe><h3>The potential for transfer learning:</h3><p>I came across two levels of transfer learning for Transformer based models:</p><ul><li>The default learning that comes baked into pre-trained models. Models like BERT/RoBERTa etc. come pre-trained on large corpora, and give us a starting point</li><li>Fine-tuning the architecture for task specific learning, which is typically how these architectures are used today (e.g. building classifiers/Q&amp;A systems with a dataset from the domain)</li></ul><p>The problems I work on generally do not have domain specific labeled datasets. This led me to explore the<strong> third option:</strong></p><ul><li><strong>What if I fine-tune the models, but on a dataset that comes from a different domain? If I make sure that the objective is similar, can I still transfer learn, even though I know there will be a covariate shift?</strong><em>(covariate shift is the change in the distribution of the input variables present in the training and the test/realtime data).</em></li></ul><p>To understand if this method of transfer learning works, let’s do a quick experiment. Let’s pick sentiment/polarity as the objective for our experimentation.</p><p>We take the pre-trained RoBERTa model, <strong>fine-tune </strong>the model on the <strong>training</strong> <strong>set</strong> from the <strong>IMDB 50K movie reviews</strong>, and then pick our <strong>evaluation dataset</strong> as follows:</p><ul><li>2 sentences from the <strong>IMDB 50k movie reviews TEST</strong> dataset</li></ul><pre><strong>Positive</strong>: <em>&#39;This is a good film. This is very funny. Yet after this film there were no good Ernest films!&#39;</em></pre><pre><strong>Negative</strong>: <em>&#39;Hated it with all my being. Worst movie ever. Mentally- scarred. Help me. It was that bad.TRUST ME!!!&#39;</em></pre><ul><li>2 sentences from <strong>Amazon fine food reviews, </strong>which is a dataset from a <strong>completely different domain. </strong>We will use this only for evaluation</li></ul><pre><strong><em>Positive</em></strong><em>: &#39;This taffy is so good.  It is very soft and chewy.  The flavors are amazing.  I would definitely recommend you buying it.  Very satisfying!!&#39;</em></pre><pre><strong>Negative</strong>: <em>&quot;This oatmeal is not good. Its mushy, soft, I don&#39;t like it. Quaker Oats is the way to go.&quot;</em></pre><p>We then extract and visualize sentence similarity on both the base pre-trained model (RoBERTa architecture in this case), and on the fine-tuned model on the same architecture</p><p>The code to fine-tune BERT is available <a href="https://github.com/nidharap/Notebooks/blob/master/IMDB_Classification.ipynb">here</a>.</p><h3><strong>Comparison:</strong></h3><ol><li><strong>Lets do our first comparison by visualizing cosine similarity between sentence vectors obtained by averaging word vectors, that are themselves an averaged version from the last four layers</strong> (<em>I know this was a mouthful, but if you need clarification on any of these, feel free to scroll up where we discussed each of them in detail</em>).</li></ol><p><strong><em>Legend: The yellow circles are positive, while the pink circles are negative</em></strong></p><p>Figure 11 below shows the the visualization run on the pre-trained model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yOKN_7KKfLhwypO_70-Aqw.png" /><figcaption>Figure 11 Pre-trained model: The vectors are extremely close to each other. We will need to zoom in to understand better. <em>The yellow circles are positive, while the pink circles are negative</em></figcaption></figure><p>Figure 12 below shows the same plot has Figure 11 but zoomed in (<em>notice the axes have a different range</em>). This shows that while the distance between the vectors is really small, after zooming in, we see that the model does attempt to place the sentences discussing the subject (food) closer to each other, favoring the subject of discussion more than the polarity of the sentence (<em>see the bottom two circles, one yellow and one pink</em>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kMG87NjzkXFk9iGq8ZZecw.png" /><figcaption>Figure 12 Pre-trained model: After zooming in, we see that it does attempt to place the sentences discussing the subject (food) closer to each other, favoring the subject of discussion more than the polarity of the sentence. The yellow circles are positive, while the pink circles are negative</figcaption></figure><p>Now let’s look at the same sentences passed through the fine-tuned model in Figure 13 below. Notice how the sentences are much closer based on the polarity. As you can notice, it has moved its focus from the subject of discussion (food/movie) to polarity (positive vs negative): The positive sentence from the movie review data is closer to the positive sentence from the food review dataset, as is the case with the negative examples. This is exactly what we needed !<strong> We wanted to use a dataset from a completely different domain, but with a similar labeling objective, to transfer learn!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LfMi_uFs-bJOVDdcZmkTOw.png" /><figcaption>Figure 13 Fine-tuned model: As you can notice, it has moved its focus from the subject of discussion (food vs movie) to polarity (positive vs negative). The yellow circles are positive, while the pink circles are negative</figcaption></figure><p><strong>2. Let’s do our second round of comparison by visualizing the Word Movers Distance (WMD) calculated on word vectors averaged from the last four layers.</strong></p><p>Figure 14 below shows similar characteristics as the models above. The subject of discussion (food) still seems to be the focus. One main difference here is that Word Movers Distance (WMD) is able to tease out the distances better than the earlier method (<em>applying cosine distance on averaging word vectors across sentences</em>), even on the base model i.e. there was no need to zoom in here. This shows that averaging of word vectors may have unintended consequences for a downstream task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j7Rz2AnmoA8to1bw-TIIHA.png" /><figcaption>Figure 14: The distance metric, Word Movers Distance (WMD), shows similar characteristics, but can help differentiate sentences better than averaging methods. The yellow circles are positive, while the pink circles are negative</figcaption></figure><p>Figure 15 below shows the same WMD metric on the four sentences using the Fine-tuned model, which again shows that we were able to “shift” the focus of the model towards polarity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KXJ2MjJy-4lTNJVDMkugmg.png" /><figcaption>Figure 15: WMD metric on the four sentences using the Fine-tuned model. The yellow circles are positive, while the pink circles are negative</figcaption></figure><p><strong>In summary, the ability to transfer-learn from unrelated domain datasets will open more avenues for projects that struggle with data today. The power of transformers now can enable companies to leverage previously unusable datasets, and not have to spend time creating labelled datasets.</strong></p><p>I hope this article was helpful. There are few other topics like data augmentation in NLP, model interpretation via techniques like LIME (Local interpretable model-agnostic explanations) etc. that interest me and I do plan to explore them in future posts. Until then, thanks for reading!</p><h3><strong>References:</strong></h3><ul><li><a href="https://huggingface.co/transformers/model_doc/bert.html#bertmodel">BERT - transformers 3.0.2 documentation</a></li><li><a href="https://arxiv.org/abs/1810.04805">BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding</a></li><li><a href="http://jalammar.github.io/illustrated-transformer/">The Illustrated Transformer</a></li><li><a href="https://arxiv.org/abs/2005.00928">Quantifying Attention Flow in Transformers</a></li><li><a href="https://samiraabnar.github.io/articles/2020-04/attention_flow">Quantifying Attention Flow in Transformers | Samira Abnar</a></li><li><a href="https://seaborn.pydata.org/generated/seaborn.heatmap.html">seaborn.heatmap - seaborn 0.12.2 documentation</a></li><li><a href="https://github.com/src-d/wmd-relax">src-d/wmd-relax</a></li><li><a href="https://www.kaggle.com/snap/amazon-fine-food-reviews">Amazon Fine Food Reviews</a></li><li><a href="https://www.kaggle.com/atulanandjha/imdb-50k-movie-reviews-test-your-bert">IMDB 50K Movie Reviews (TEST your BERT)</a></li><li><a href="https://en.wikipedia.org/wiki/Multidimensional_scaling">Multidimensional scaling</a></li><li><a href="https://stats.stackexchange.com/questions/303050/word-movers-distance-calculation-between-word-pairs-of-two-documents">Word Mover&#39;s distance calculation between word pairs of two documents</a></li></ul><p><a href="https://arxiv.org/pdf/1906.05714.pdf">https://arxiv.org/pdf/1906.05714.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d38c75f574fb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/beyond-classification-with-transformers-and-hugging-face-d38c75f574fb">Beyond Classification With Transformers and Hugging Face</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Pipelines in Fastai (v1)]]></title>
            <link>https://ndharap.medium.com/data-pipelines-in-fastai-v1-4c927d7757d2?source=rss-fdefd04bcc7a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c927d7757d2</guid>
            <category><![CDATA[ml-pipeline]]></category>
            <category><![CDATA[fastai-datablocks-api]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-block-api]]></category>
            <category><![CDATA[ds-in-the-real-world]]></category>
            <dc:creator><![CDATA[Nikhil Dharap]]></dc:creator>
            <pubDate>Tue, 30 Jun 2020 22:41:16 GMT</pubDate>
            <atom:updated>2020-07-01T06:35:23.131Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Pipelines in Fastai (data blocks API v1)</h3><p>One of the most useful features that fastai brings to the table is its datablock api. I have been part of many machine learning projects, and one common theme across them has been the large amount of time I spend creating pipelines that can work across training/validation sets consistently.</p><p>I must admit that the the first time I started looking through fastai datablock apis to handle data, I was a little confused. It took me some time to grasp the framework, going through their docs, forums and blogs. Once I was past the hump, I could see why it’s built the way it is, and the value it brings: ease of use &amp; flexibility to customize. While it may be intuitive for people to read and follow code, it has always been easier for me to visualize things in flow/block diagrams. Diagrams help me first look at things from a birds eye view, understand the overall objective, and then provide me ways to go deep in certain directions. I looked for blogs/articles/docs that could provide me a few diagrams to start quick, but I could not find any. In this article, I am hoping that I could demonstrate the api framework with some quick flow diagrams, which hopefully paint the larger picture, and help folks like me navigate the large framework faster.</p><p><strong><em>Note</em></strong><em>: While it is not necessary to understand Object Oriented Programming (OOP) in python in depth, a basic understanding of OOP concepts in python will help a long way, especially when you need to dig through most of the pytorch and fastai codebase. There are plenty of youtube videos taking you through the concepts. I found the video playlist by Corey Schafer quite helpful in brushing up my OOP concepts: </em><a href="https://youtu.be/ZDa-Z5JzLYM"><em>Link</em></a></p><p>Most of the ML pipelines consist of the following steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Of9MmM3vb3Tep4tjgpA7Aw.png" /><figcaption>Figure 1: Key steps in a typical pipeline for deep learning</figcaption></figure><p><strong><em>Note</em></strong><em>: Most real life projects do not give us a ready dataset like we would find in a kaggle competitions. There is plenty of work that goes into getting a dataset labelled and prepared. Since the scope of this article was to focus on what fastai datablock api can provide, I am assuming that we already have a ready dataset (labelled for the most part, except in cases like language modeling which can be converted into a labelled dataset).</em></p><h3>Data Ingestion and Organization</h3><p>Let’s start investigating the actual building blocks of the api, and how they flow from one to the other. The first three points above (reading data and splitting it into multiple ways) can be achieved by the following process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EG334HbiJRDcCttEltrkLQ.png" /><figcaption>Figure 2: Reading and splitting data into different ways</figcaption></figure><p>As you can see above, the main build block is the <strong>ItemList</strong> class, which stores a list of items and lets you access them in different ways. <strong>ItemLists</strong> is just a list of ItemList. <strong>LabelList</strong> is a group of ItemList with X and y components, a <strong>LabelLists</strong> is a list of LabelList.</p><p>Let’s try to look at the ItemList class, that is at the center of all of this: (<em>I generated this using pyreverse, a tool to generate UML diagrams from a code base: </em><a href="https://pypi.org/project/pyreverse/"><em>Link</em></a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cKpPNrV-CwGR5DEYLiP-KQ.png" /><figcaption>Figure 3: The ItemList class and its attributes and methods</figcaption></figure><p>As you can observe above, the ItemList class has a number of predefined methods that could be very useful in achieving the above flow in Figure 2.</p><p>Let’s apply them to previous flow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v3xsWUkzDQddAPqr_o0Kyg.png" /><figcaption>Figure 4: Tie the methods to the flow diagram</figcaption></figure><p>From a code perspective, it is as easy as the writing 3 lines code, chained one after the other (<a href="https://github.com/fastai/course-nlp/blob/master/5-nn-imdb.ipynb"><em>source</em></a>)-</p><pre>TextList.from_csv(path, &#39;texts.csv&#39;, cols=&#39;text&#39;)<br>.split_from_df(col=2)<br>.label_from_df(cols=0)</pre><p>While I looked at that code, I started wondering why does it say TextList instead of ItemList. The reason is that TextList is a <strong>subclass</strong> of ItemList (see <a href="https://github.com/fastai/fastai/blob/master/fastai/text/data.py">here</a>). So the idea is to subclass ItemList for the specific type of data elements (<em>example links: </em><a href="https://github.com/fastai/fastai/blob/master/fastai/text/data.py"><em>TextList</em></a><em>, </em><a href="https://github.com/fastai/fastai/blob/master/fastai/vision/data.py"><em>ImageList</em></a><em>, </em><a href="https://github.com/fastai/fastai/blob/master/fastai/tabular/data.py"><em>TabularList</em></a><em> etc.</em>), and make use of the methods defined in the super class (<em>link: </em><a href="https://github.com/fastai/fastai/blob/master/fastai/data_block.py"><em>ItemList</em></a>) as needed. In general, you can walk over to the documentation page <a href="https://docs.fast.ai/applications.html"><em>here</em></a> for your data type OR go to the code base and look for your data type folder and the corresponding data.py file.</p><p>Now that we have our data split multiple ways, let’s look at transformations on our data.</p><h3><strong>Transformations</strong></h3><p>There are two types of transformations that fastai supports:</p><ol><li><strong>Transforms</strong>: Need no learning from the training data, and can be applied directly to every data points (for example image data augmentation). This fits quite well with the <strong><em>sklearn methodology of transforms with no fit implementation</em></strong></li><li><strong>Processors</strong>: Needs to learn from training set and then apply to test set for specific aspects. <strong><em>I am using the term learning very loosely here</em></strong>, but the it fits very well with the <strong><em>sklearn methodology with both fit and transform implemented</em></strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zhiQYJXT7X5CI8MCftCVPA.png" /><figcaption>Figure 5: Processors Vs Transforms</figcaption></figure><p>There are a whole bunch of transforms already supported in the library. Like data.py, we have a transforms.py that provides all the transformations supported by fastai in each of the folders (text, vision and tabular). The docs can be found <a href="https://docs.fast.ai/applications.html">here</a>. Just navigate to any of the transform section for the corresponding transformations. You can also right your own transformation class or method (<em>like various methods </em><a href="https://github.com/fastai/fastai/blob/master/fastai/vision/transform.py"><em>here</em></a>) OR a custom processor classes that inherits from the Processor class (<em>for example see the CategoryProcessor </em><a href="https://github.com/fastai/fastai/blob/master/fastai/data_block.py"><em>here</em></a>)</p><h3>Data Bunch and Data Loaders</h3><p>Finally, the last step is the be able to take the dataset and create mini batches of data that could be fed based a batch size. This is done in the data loader class.</p><p>Let’s try to put all of this together to see the parallels between our objective of creating the pipeline and how it looks in fastai -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wBQDBSs_Go7jYw0gHFMlgQ.png" /><figcaption>Figure 6: The full pipeline with fastai datablocks</figcaption></figure><p>As you can see above, the data loader class just breaks the date down based on batch size, and yields one batch at at time. This is done separately for both train and val sets.</p><p>Data bunch is just another wrapper that can wrap a data loader and any additional info like number of classes that we could use while creating the model.</p><h3>References:</h3><p><a href="https://dev.fast.ai/tutorial.datablock#Building-a-DataBlock-from-scratch">Data block tutorial</a></p><p>Datablock Tutorial by Jeremy:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FhPQKzsjTyyQ%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DhPQKzsjTyyQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FhPQKzsjTyyQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/be32fd53b9bb27566d31d13e52d3cd18/href">https://medium.com/media/be32fd53b9bb27566d31d13e52d3cd18/href</a></iframe><ul><li><a href="https://www.fast.ai/2020/02/13/fastai-A-Layered-API-for-Deep-Learning/">fastai-A Layered API for Deep Learning</a></li><li><a href="https://github.com/fastai/course-nlp/blob/master/5-nn-imdb.ipynb">fastai/course-nlp</a></li><li><a href="https://blog.usejournal.com/finding-data-block-nirvana-a-journey-through-the-fastai-data-block-api-c38210537fe4">Finding Data Block Nirvana (a journey through the fastai data block API)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c927d7757d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>