<?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[Illuin - Medium]]></title>
        <description><![CDATA[Illuin Technology builds strategic AI projects (Data Science, NLP) and new tech interactions (Mobile, AR, VR, Voice) - Medium]]></description>
        <link>https://medium.com/illuin?source=rss----7e66f049dad0---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Illuin - Medium</title>
            <link>https://medium.com/illuin?source=rss----7e66f049dad0---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 07:15:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/illuin" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Dependency injection made easy in Python]]></title>
            <link>https://medium.com/illuin/dependency-injection-made-easy-in-python-45ece11efeca?source=rss----7e66f049dad0---4</link>
            <guid isPermaLink="false">https://medium.com/p/45ece11efeca</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Thomas Richard]]></dc:creator>
            <pubDate>Tue, 20 Oct 2020 17:58:58 GMT</pubDate>
            <atom:updated>2020-10-21T08:43:30.386Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I6UkvxUjvceCo9rWHIZJdA.png" /><figcaption>Dependency injection is not always harmful</figcaption></figure><p><a href="https://github.com/illuin-tech/opyoid"><em>Discover Opyoid</em></a><em>, our new dependency injection library made in Python, featuring typings, modules, auto bindings and more !</em></p><h3>Why do we need dependency injection ?</h3><p>Let’s use an example project to illustrate this article. Imagine that you are writing code for a chatbot application. You want to reuse some classes between your bots so you don’t have to redo all your work every time. You start by writing the main classes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7589d9f8197067179087bd9f69481746/href">https://medium.com/media/7589d9f8197067179087bd9f69481746/href</a></iframe><p>The <em>Chat</em> class is fairly simple to understand. It needs a source that provides the user messages, then gives it to the answer generator to get the corresponding answer, and the output writer is responsible to handle the answer. You can optionally add a logger that will write the conversation to a file.</p><p>The <em>UserMessageSource</em> and <em>OutputMessageWriter</em> are abstract classes that can be implemented to customize the behavior of the chatbot.</p><p>A realistic scenario could be to create two different implementations. The CLI version reads the input from the console and writes the answers to it, this is useful for debugging on a local environment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3828c65afe428d20a697dc741e42eea/href">https://medium.com/media/b3828c65afe428d20a697dc741e42eea/href</a></iframe><p>This simple version can read input from the CLI and print the answers, as well as log the conversation in a text file.</p><p>A production-ready version could be connected to a Message Queuing solution such as <a href="https://www.rabbitmq.com/">RabbitMQ</a> to map a stream of user inputs into the corresponding bot answers. Since the implementation details are not really relevant to this article, here is a simple fake version:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56ed46ab7c2d762ffb1e72a32a138cd5/href">https://medium.com/media/56ed46ab7c2d762ffb1e72a32a138cd5/href</a></iframe><p>In this version, we need a <em>MqConfig</em> instance that will be shared between the <em>MqUserMessageSource</em> and the <em>MqOutputWriter</em>. The <em>ConversationLogger</em> is not used, it could be added as a independent MQ consumer.</p><p>This code works, but has a few pain points:</p><ul><li>Creating a new configuration: implies instantiating a new <em>Chat</em> and all its dependencies. If this doesn’t seem like much work to you, remember it’s just an example, you probably wouldn’t want to do it with over 100 classes of dependencies.</li><li>Adding/removing/swapping a feature: changing a group of logically linked dependencies can be tedious (you have to remove 2 classes and add 3 more to have a MQ-connected chatbot).</li><li>Adding a dependency to a class breaks all configurations: if the conversation logger requires a log format, you would have to check all configurations using one and edit them manually.</li><li>It’s a lot of boilerplate code, error-prone and without great value.</li></ul><p>One solution to mitigate this is to use dependency injection to automatically link each class to its dependencies.</p><h3>How does it work ?</h3><p>Here are a few examples of how you can use opyoid to simplify your application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e16dd39a184cdd2ae40f1669990f0a4/href">https://medium.com/media/3e16dd39a184cdd2ae40f1669990f0a4/href</a></iframe><p>As you can see, you create bindings to configure which classes should be instantiated, and opyoid does the rest.</p><ul><li>Here <em>Chat</em> requires an instance of <em>UserMessageSource</em>, and <em>CliUserMessageSource</em> is bound to this type so it gets instantiated when needed. Same thing for the <em>OutputWriter</em>, that is bound to the CLI version. When you want to bind a class to itself, such as <em>Chat</em> or <em>AnswerGenerator</em>, you don’t have to declare it twice.</li><li>The ConversationLogger is bound to an instance of itself, it will be used directly when needed.</li><li>All the bindings are given to an <em>Injector</em>, that you can then use to instantiate new objects.</li><li>Notice that the only requirement for binding a class is that its constructor uses type hints, in our example we didn’t change the classes in any way.</li><li>Also the order of the bindings does not matter, you can bind a class before or after its dependencies, so you don’t have to think about it.</li></ul><p>What does the MQ version look like now ?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ec731e4f0717f3bf73869c1a4a3f6e9/href">https://medium.com/media/0ec731e4f0717f3bf73869c1a4a3f6e9/href</a></iframe><p>Notice how we used an <em>InstanceBinding</em> for the <em>MqConfig</em>, this is useful when you need to inject configuration dataclasses that contain primitive types such as strings, ints or booleans. This <em>MqConfig</em> has been automatically linked to all MQ connectors, so adding a new one would not require additional configuration except the class itself. You can also see that removing the <em>ConversationLogger </em>binding is not a problem since it has a default value in the <em>Chat </em>constructor, only the parameters without a default are required.</p><h3>Further improvements</h3><blockquote>What if my code has no type hints ? Does that mean that I have to rewrite all my code so that I can use this ? And what if I depend on an external library, that I don’t have any control over ?</blockquote><p>Be reassured, you can write your own provider to wrap those classes so they can be injected too.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/155fc951a6a754ed8a48696ca6ef3684/href">https://medium.com/media/155fc951a6a754ed8a48696ca6ef3684/href</a></iframe><p>Here the <em>ChatProvider </em>will be used to create every <em>Chat</em> instance needed, even if its constructor had no type hints. Notice the <em>ProviderBinding</em> in the <em>Injector</em> initialization.</p><p>Writing your own provider can also be used to add some logic on how some classes are instantiated.</p><blockquote>Does that mean I have to create a single file with all my bindings ? I still have to duplicate a lot of bindings between my configurations.</blockquote><p>That’s why you can use modules to group your bindings, so that you can reuse them across your configurations and just pick the ones you need.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8aea443cd9291f5e516487ff279f7d5d/href">https://medium.com/media/8aea443cd9291f5e516487ff279f7d5d/href</a></iframe><p>Modules are usually used to group all classes related to a feature. By adding or removing the module, you can easily enable or disable this feature.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63c005269a899688b76c0a6fb601d26c/href">https://medium.com/media/63c005269a899688b76c0a6fb601d26c/href</a></iframe><p>You can declare as many bindings as you want in a module, and install other modules as needed, we used it here to install the <em>ChatModule</em> into the <em>CliChatModule</em>.</p><p>Note that you can still add bindings on top of the modules in your injector.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33357e68ae3248978bb1dd8a8436f75a/href">https://medium.com/media/33357e68ae3248978bb1dd8a8436f75a/href</a></iframe><blockquote>Can you do better ? You talked about reducing boilerplate code, yet I still have to write all those bindings ?</blockquote><p>Say no more:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/791408cf2cd4c1535ee1535f321750e2/href">https://medium.com/media/791408cf2cd4c1535ee1535f321750e2/href</a></iframe><p>When using the <em>auto_bindings</em> option, classes are automatically bound to themselves, so you only need to write the other bindings. You can still use modules and bindings of course, these auto bindings are only created as a last resort option. In the example we removed the ChatModule since it contained only <em>ClassBindings</em>.</p><p>Comparing it to the code we had in the beginning, we now have :</p><ul><li>automatic linking between classes and their dependencies, much less breaking changes when requirements change, automatic detection of missing dependencies</li><li>no duplication between configurations</li><li>boilerplate code reduced to the bare minimum</li></ul><h3>Why not reuse an existing library ?</h3><p>We found that the Python ecosystem was lacking solid options for that. The best library we tested was <a href="https://github.com/google/pinject">pinject</a>, but we wanted to take advantage of the typings to inject our classes. Another alternative is <a href="http://python-dependency-injector.ets-labs.org/introduction/di_in_python.html">python-dependency-injector</a>, but it still requires a lot of code to setup. Plus, it’s always more fun to do things on your own 😉.</p><p>So we decided to write a new dependency injection Python library, <a href="https://github.com/illuin-tech/opyoid">opyoid</a>, to be able to easily resolve dependencies between classes and simplify the setup in large applications.</p><p>Our main goals when writing our library were:</p><ul><li>Automatically provide dependencies to each class</li><li>Use typings to resolve them, as they are becoming the norm in Python</li><li>Be able to inject third-party classes</li><li>No mandatory decorators on all classes</li></ul><p>We also added some more advanced features that we needed:</p><ul><li>A scope for each binding to be able to share some instances throughout the code while creating multiple instances of some other classes</li><li>Providers to customize how classes are created or delay instantiation</li><li>Annotations to be able to have multiple bindings for the same type</li><li>And more…</li></ul><h3>Final words</h3><p>And there you go, now you finally have a clean and readable code split into simple classes, without the hassle of writing boilerplate code. You can easily bind new classes where needed for each feature, create modules to group them together and easily activate them. You can <a href="https://github.com/illuin-tech/opyoid">check the project on Github</a> for more examples and documentation.</p><p>Using dependency injection and especially with opyoid helped us tremendously to create modular and reusable applications, and developing on our codebase has never been so pleasurable.</p><p>Thanks for reading, you can leave a comment if you want to give some feedback on the article or the library 😊.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45ece11efeca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/illuin/dependency-injection-made-easy-in-python-45ece11efeca">Dependency injection made easy in Python</a> was originally published in <a href="https://medium.com/illuin">Illuin</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LePetit: A pre-training efficient and lightning fast French Language Model]]></title>
            <link>https://medium.com/illuin/lepetit-a-pre-training-efficient-and-lightning-fast-french-language-model-96495ad726b3?source=rss----7e66f049dad0---4</link>
            <guid isPermaLink="false">https://medium.com/p/96495ad726b3</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Vincent Micheli]]></dc:creator>
            <pubDate>Tue, 14 Jul 2020 17:35:56 GMT</pubDate>
            <atom:updated>2020-09-20T18:07:42.938Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*MoPnD6vA9wTHjdLfW7POyw.png" /><figcaption>Credits: Jérôme Daburon</figcaption></figure><p>Recent advances in language modeling have led to computationally intensive and resource demanding state-of-the-art models. In an effort towards sustainable practices, we introduce<strong> LePetit: a tiny French Language Model</strong>.</p><p>In this story we’ll also discuss why compact models are necessary and evaluate LePetit on the <a href="https://arxiv.org/abs/2002.06071">French Question Answering Dataset</a> (FQuAD) as well as the <a href="https://webis.de/data/webis-cls-10.html">Cross Lingual Sentiment</a> (CLS) dataset.</p><p>If you’re looking for a more in-depth analysis, we will soon release a research paper on the importance of pre-training data volume for compact language models. In the meantime, the model is available in the <a href="https://huggingface.co/models?search=illuin">Hugging Face collection</a>!</p><h3>The need for compact language models</h3><p><a href="https://arxiv.org/abs/1810.04805">Pre-trained</a> language models have become the norm in Natural Language Processing. These large-scale <a href="https://arxiv.org/abs/1706.03762">Transformer</a>-based networks considerably advanced the state-of-the-art in language understanding via a two-step process: self-supervised learning on a vast text corpus followed by fine-tuning on a specific downstream task.</p><p>Following these advances, the ongoing trend has been to build bigger models with an ever-increasing amount of data (e.g. <a href="https://arxiv.org/abs/1907.11692">RoBERTa</a>) and parameters (e.g. <a href="https://arxiv.org/abs/2005.14165">GPT-3</a>). However, pre-training models with billions of parameters over hundreds of gigabytes of text requires tremendous computational resources that only a few companies and institutions can afford. Besides, these cumbersome models introduce <em>significant delays at inference time</em>, especially on non-dedicated hardware. Hence, our goal is to explore model architectures and data volumes lowering the entry barrier to new research and practical applications.</p><h3>LePetit</h3><h4>Model</h4><p>LePetit was inspired by its larger relative <a href="https://arxiv.org/abs/1911.03894">CamemBERT</a>. CamemBERT is a multi-layer bidirectional Transformer with two architectures: base (12 layers, 768 hidden dimensions, 12 attention heads, 110M parameters) and large (24 layers, 1024 hidden dimensions, 16 attention heads, 355M parameters). It is very similar to RoBERTa. The main differences are the use of whole-word masking and <a href="https://arxiv.org/abs/1808.06226">SentencePiece</a> tokenization instead of subword-masking and <a href="https://arxiv.org/abs/1609.08144">WordPiece</a> tokenization. RoBERTa itself improves upon <a href="https://arxiv.org/abs/1810.04805">BERT</a> by aggregating several modifications on top of the original architecture such as removing the next sentence prediction task, dynamic masking and training with larger batches on more data.</p><p>LePetit has what we call a <em>small</em> architecture (12 layers, 256 hidden dimensions, 4 attention heads, 17M parameters). The main difference with the original CamemBERT lies in the use of subword-masking. Indeed, the authors later found out that whole-word masking had at best a marginal impact on downstream task performance.</p><p>Apart from inference speed and size considerations, two main factors explain this architectural choice:</p><ul><li>This is almost the same architecture as <a href="https://arxiv.org/abs/2003.10555">ELECTRA-SMALL++</a>, a recently released compact language model. While ELECTRA and CamemBERT differ in many regards (ELECTRA being trained as a discriminator rather than a generator), prior experiments conducted by the ELECTRA team give us an acceptable set of hyperparameters when pre-training and fine-tuning the model.</li><li>The “<a href="https://arxiv.org/abs/1908.08962">Well-Read Students Learn Better</a>” authors observed that depth should be prioritized over width when pre-training compact models. Note that even though for a given parameters budget, depth outperforms width, it comes at a cost in inference speed as observed by the <a href="https://arxiv.org/abs/1910.01108">DistilBERT</a> team.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*OpGDalXdKFYMTN3nHr6FDg.png" /><figcaption>Model size and inference speed: LePetit vs CamemBERT</figcaption></figure><p>As illustrated above, LePetit is much smaller and faster than its larger siblings. It provides, respectively, a <strong>4.5-fold and 15-fold inference speed-up</strong> when compared to CamemBERT-base and CamemBERT-large while being <strong>6.2 and 18.8 times smaller.</strong></p><p>Therefore, LePetit should be used in memory or time-constrained applications. For instance, it may find its purpose on smartphones or in information retrieval systems.</p><h4>Dataset</h4><p><a href="https://traces1.inria.fr/oscar/fr/">OSCAR</a> is a recently released large-scale multilingual open source corpora obtained by language classification and filtering of the <a href="https://commoncrawl.org/about/">Common Crawl </a>corpus. The whole French part amounts to 138 GB of text. <strong>LePetit was pre-trained on only 2 GB but our experiments revealed that models with similar performance are obtained with as little as 100 MB!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*DZ9zmasR8Ecrj9RxhTAk4Q.png" /><figcaption>Credits: traces1.inria.fr/oscar/fr</figcaption></figure><h4>Pre-training phase</h4><p>LePetit is pre-trained with the standard masked language modeling (MLM) objective. MLM consists in training a model to predict masked words in a paragraph. That knowledge is then transferred to the downstream task of our choosing, such as <a href="https://rajpurkar.github.io/SQuAD-explorer/">Question Answering</a> or <a href="https://cims.nyu.edu/~sbowman/multinli/">Natural Language Inference</a>, where the model is further fine-tuned.</p><p><strong>Pre-training is conducted for 200k training steps, which only took 35 hours on a single </strong><a href="https://www.nvidia.com/fr-fr/data-center/tesla-v100/"><strong>Tesla V100 GPU</strong></a><strong>!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b27A63yjLGaBSpTQ.png" /><figcaption>The MLM setup. Credits: <a href="http://jalammar.github.io/illustrated-bert/">http://jalammar.github.io/illustrated-bert/</a>. If you’re looking to deepen your understanding of Transformers, I highly recommend checking out <a href="http://jalammar.github.io/">Jay Alammar’s blog</a>.</figcaption></figure><h3>Downstream Evaluation</h3><h3>Text Classification</h3><h4>Dataset</h4><p>The French part of the <a href="https://webis.de/data/webis-cls-10.html">Cross Lingual Sentiment</a> (CLS) dataset is one of the <a href="https://arxiv.org/abs/1912.05372">FLUE </a>tasks. It consists of 4000 Amazon reviews for three product categories: books, DVD, and music. We consider the music category. Reviews have an associated rating, ranging from 1 to 5. Those rated higher than 3 are labelled as positive while the rest is labelled as negative (3’s are excluded). Given a review, the task consists in predicting whether it is positive or negative.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JQhAqXTGki87bQARVKP-eQ.png" /><figcaption>Amazon reviews are wild</figcaption></figure><h4>Fine-tuning phase</h4><p>After pre-training, LePetit is fine-tuned on the text classification task with the following method: a review goes through the model and a representation of a token prepended to the review is produced. Indeed, this token acts as a paragraph-level embedding. It is then fed to a classification head tasked to discriminate between positive and negative reviews.</p><h4>Results</h4><p><strong>LePetit and CamemBERT-base achieve respectively an accuracy score of 88 and 95 on the CLS test set.</strong></p><h3>Question Answering</h3><h4>Dataset</h4><p>The French Question Answering Dataset (<a href="https://arxiv.org/abs/2002.06071">FQuAD</a>) is a recently released French native reading comprehension dataset. We consider its new 1.1 version. It consists of 60,000 questions and answers gathered on a set of 1,769 high-quality Wikipedia articles. In many aspects, it is the French equivalent of <a href="https://arxiv.org/abs/1606.05250">SQuAD 1.1</a>. Given a question and a paragraph, the task consists in extracting from the paragraph the span of text answering the question.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JfQTbwXCPHKnWwKbH7Ffag.png" /><figcaption>Examples with various inference types</figcaption></figure><h4>Fine-tuning phase</h4><p>After pre-training, LePetit is fine-tuned on the question answering task with the same span prediction method as <a href="https://arxiv.org/abs/1810.04805">BERT</a>. That is, for a given question/paragraph pair, it predicts for each token in the paragraph its likelihood of being either the start or the end of the expected answer. All the tokens in-between these start and end delimiters (included) will constitute the returned answer.</p><h4>Results</h4><p><strong>LePetit reaches an F1 score of 72 and an Exact Match of 58 on the FQuAD validation set.</strong> This means that, in average, 72% of the tokens flagged as an answer by the model correspond to the ground truth answer and that 58% of the predicted answers match perfectly the expected answers.</p><p>For anchoring, LePetit “fine-tuned” directly on FQuAD without a pre-training phase achieves an F1 score of only 17.76. Regarding larger architectures, CamemBERT-base and CamemBERT-large models trained with a standard two-step process obtain respectively an F1 score of 88 and 92.</p><h4>Learning from the big cheese: distillation</h4><p>While <a href="https://arxiv.org/abs/1910.06360">question answering is a notoriously difficult task for compact models </a>and performance gaps between compact and large models are smaller on <a href="https://arxiv.org/abs/1804.07461">GLUE</a>-like tasks, LePetit can still learn how to answer questions from its elders!</p><p>This will be the subject of a second part investigating <a href="https://arxiv.org/abs/1503.02531">classical</a> and <a href="https://arxiv.org/abs/2002.10957">advanced</a> distillation strategies. If you want to know more about how LePetit reached an F1 score of 80+ by distilling the knowledge of CamemBERT, stay tuned!</p><h4>To sum up:</h4><ul><li>We introduced LePetit, a tiny French Language Model.</li><li>We showed that it is much smaller and faster than existing French models.</li><li>We saw that it is pre-training efficient, relying on few data and computational resources.</li><li>We evaluated LePetit on two downstream tasks, comparing it to larger models.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96495ad726b3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/illuin/lepetit-a-pre-training-efficient-and-lightning-fast-french-language-model-96495ad726b3">LePetit: A pre-training efficient and lightning fast French Language Model</a> was originally published in <a href="https://medium.com/illuin">Illuin</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Learning has (almost) all the answers: Yes/No Question Answering with Transformers]]></title>
            <link>https://medium.com/illuin/deep-learning-has-almost-all-the-answers-yes-no-question-answering-with-transformers-223bebb70189?source=rss----7e66f049dad0---4</link>
            <guid isPermaLink="false">https://medium.com/p/223bebb70189</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Vincent Micheli]]></dc:creator>
            <pubDate>Mon, 30 Mar 2020 13:50:16 GMT</pubDate>
            <atom:updated>2020-12-23T18:51:10.518Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E-JQ3oIrLT0Tkfsn.jpg" /><figcaption>Credits: applovin.com</figcaption></figure><p>Boolean Question Answering may seem like an easy task but it is surprisingly difficult and current baselines are not remotely close to human performance levels.</p><p>In this story we’ll see how to use the <a href="https://github.com/huggingface/transformers">Hugging Face Transformers</a> and <a href="https://pytorch.org/">PyTorch</a> libraries to fine tune a Yes/No Question Answering model and establish state-of-the-art* results. You can find the full code notebook <a href="https://colab.research.google.com/drive/1M72jopk0AECxQlHAOVMZjEj-ibR293xk">here</a>.</p><p>Disclaimer: This post aims at delivering a short and easy-to-use pipeline for Boolean Question Answering. If you’re looking for some more background reading I recommend having a look at this <a href="https://medium.com/illuin/building-an-open-domain-question-answering-pipeline-in-french-97304e63c369">comprehensive review of the current NLP/Question Answering landscape</a>.</p><h3>Why Boolean Question Answering is amazing</h3><p>These days <a href="https://rajpurkar.github.io/SQuAD-explorer/">Extractive Question Answering</a> gets all the hype. However, ignoring Yes/No Question Answering would be missing half of the picture. Indeed, answering closed-form questions has tremendous value. Here is a non-exhaustive list of use cases in the industry:</p><ul><li>Search engines: knowledge base querying, conversational agents…</li><li>Automatic information extraction: form filling, parsing large documents…</li><li>Voice user interfaces: smart assistants, vocal conversation parsing…</li></ul><p>Now that we have established that Yes/No Question Answering is awesome, let’s have a look at the data.</p><h3>Dataset: BoolQ</h3><p><a href="https://arxiv.org/abs/1905.10044">BoolQ</a> is a reading comprehension dataset built by researchers from Google AI Language. An example in the dataset consists of a question, a paragraph and an answer which is either yes or no.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*vPkHNknABIZLsa0oA7WU4Q.png" /><figcaption>Examples</figcaption></figure><p>The data collection pipeline is the following (a more detailed explanation is given in the paper):</p><ul><li>Questions originate from past queries to the Google search engine</li><li>They are kept if a Wikipedia article is returned</li><li>In those instances, the question/article pairs are given to a human for annotation.</li><li>The annotator finds a passage within the article answering the question and labels the answer</li><li>question/passage/answer pairs are returned</li></ul><p>Ultimately 13K pairs are gathered from this pipeline along with 3K pairs from the <a href="https://research.google/pubs/pub47761/">Natural Questions</a> training set. These examples are split into a 9.4K train set, 3.2K dev set and an unreleased 3.2K test set.</p><p>As shown below, various kinds of inference are necessary to answer the questions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lTiSYlSXphWsb4QcbBdkbg.png" /><figcaption>Inference types</figcaption></figure><p>The BoolQ team obtained its best results with <a href="https://arxiv.org/abs/1810.04805">BERT-large</a> pre-trained on the <a href="https://www.nyu.edu/projects/bowman/multinli/">MultiNLI</a> dataset. Note that the majority-baseline yields an accuracy of 62% while human annotators reached 90% accuracy (on 110 cross-annotated examples).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*3ikYQ8Ko9Um9gI4k-j7wlg.png" /><figcaption>BoolQ results</figcaption></figure><p>These results show the power of Transformer models for language understanding. However, as we will see, there is still room for improvement!</p><h3>Model: RoBERTa</h3><p><a href="https://arxiv.org/abs/1907.11692">RoBERTa</a>: <em>A Robustly Optimized BERT Pretraining Approach</em> is a language model released by researchers from Facebook AI. In a nutshell, BERT’s little sister is the aggregation of several improvements added on top of the original BERT architecture. The key differences are the following (a more thorough analysis is conducted in the paper):</p><ul><li>Masked language modelling (MLM) is done with dynamic masking rather than static masking (Section 4.1)</li><li>The Next Sentence Prediction training objective is dropped altogether (Section 4.2)</li><li>500K optimization steps are performed on mini batches of size 8000 rather than 1000K steps on mini batches of size 256 (Section 4.3)</li><li>Text encoding is handled by an implementation of BPE using bytes as building blocks rather than unicode characters (Section 4.4)</li><li>Pretraining over more data (from 16 GB to 160 GB) as explained in Section 5</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/0*GYb7J0SKoj7WL_1q.jpg" /><figcaption>When you ask Vegeta about RoBERTa’s batch size</figcaption></figure><p>RoBERTa outperforms BERT on all 9 of the <a href="https://gluebenchmark.com/leaderboard">GLUE</a> tasks as well as on the <a href="https://rajpurkar.github.io/SQuAD-explorer/">SQuAD</a> leaderboard. This is quite impressive considering that RoBERTa and BERT share the same MLM pretraining objective and architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BJFYqzUVt60RhkifEKnB-g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*N0u0cClwDJZ8M8aXhyq31g.png" /><figcaption>GLUE and SQuAD results</figcaption></figure><p>According to the authors “this raises questions about the relative importance of model architecture and pretraining objective, compared to more mundane details like dataset size and training time that we explore in this work”. However, <a href="https://arxiv.org/abs/1909.11942">ALBERT</a> and <a href="https://github.com/google-research/electra">ELECTRA</a> are the newest kids in the block and they’ve set the bar even higher in the GLUE and SQuAD leaderboards.</p><h3>Hands-on Yes/No Question Answering</h3><p>Now that we are acquainted with the dataset and model, let’s get to work!</p><h4>Mission statement:</h4><p>Beat the development set results obtained by the BoolQ team. RoBERTa will be our weapon of choice.</p><h4>Setup</h4><p>The training and development sets can be downloaded at:</p><p><a href="https://github.com/google-research-datasets/boolean-questions">google-research-datasets/boolean-questions</a></p><p>Regarding your development environment I suggest using Google Colab since it offers free GPUs.</p><p>You will need to install the following libraries:</p><pre>pip install torch torchvision<br>pip install transformers<br>pip install pandas<br>pip install numpy</pre><p>And you can download the data with the following commands:</p><pre>gsutil cp gs://boolq/train.jsonl .<br>gsutil cp gs://boolq/dev.jsonl .</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70fa8ee51bb7053fc43dbe2356e5061a/href">https://medium.com/media/70fa8ee51bb7053fc43dbe2356e5061a/href</a></iframe><h4>Model loading</h4><p>Thanks to the Transformers library, loading a model and its associated tokenizer is painless. We start with RoBERTa-base (125M parameters). As for the optimizer, we will use Adam and the learning rate recommended in the BoolQ paper.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/234e346ba671df6d60ef0f5502e5211a/href">https://medium.com/media/234e346ba671df6d60ef0f5502e5211a/href</a></iframe><h4>Data loading</h4><p>First, we define a helper function to handle the tokenization process. Indeed, encode_data will take care of the following steps:</p><ul><li>Split the questions and passages into tokens</li><li>Add the sentence start token &lt;s&gt; and the &lt;/s&gt; token denoting the separation between question and passage as well as the end of the input</li><li>Map the tokens to their IDs</li><li>Pad (with the &lt;pad&gt; token) or truncate every question/passage pair to a max_seq_length</li><li>Produce attention masks to discriminate relevant tokens from padding tokens</li></ul><p>Note that max_seq_length has to be smaller than 512 which is the standard input capacity for BERT-like models.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5062225f96dc16c04749b0e68940a4d0/href">https://medium.com/media/5062225f96dc16c04749b0e68940a4d0/href</a></iframe><p>Now that the data has been converted to RoBERTa-friendly features, we are left with building PyTorch Dataloaders.</p><p>Feel free to play with the batch_size parameter but keep in mind that larger batch sizes will require more GPU memory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/177fd6f97d6c12ac4696cd2f167db46f/href">https://medium.com/media/177fd6f97d6c12ac4696cd2f167db46f/href</a></iframe><h4>Training and Evaluation</h4><p>The procedure consists in two phases that we alternate every epoch:</p><p><strong>Training:</strong></p><ul><li>Sample a batch and load it into the GPU if we have one</li><li>Feed it to the model which will return the batch loss</li><li>Backpropagate the loss and clip the gradients to avoid <a href="https://deepai.org/machine-learning-glossary-and-terms/exploding-gradient-problem">exploding gradients</a></li><li>Perform an optimization step</li></ul><p><strong>Evaluation:</strong></p><ul><li>Sample a batch and load it into the GPU if we have one</li><li>Feed it to the model which will return the batch logits</li><li>Use the logits to make predictions</li><li>Compute the accuracy of our model</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8c1d3d4a61b9b32b49347b172c9f5d8/href">https://medium.com/media/f8c1d3d4a61b9b32b49347b172c9f5d8/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4146fb6edb223808e1eeb875619e69d3/href">https://medium.com/media/4146fb6edb223808e1eeb875619e69d3/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4619fa5c7ce6d5ac84dcb3cb1283ed87/href">https://medium.com/media/4619fa5c7ce6d5ac84dcb3cb1283ed87/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*RDD8BkLSY8AhHxPfUHduig.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*aJBOK5zoy3uyV3Az6npBbg.png" /><figcaption>RoBERTa-base results</figcaption></figure><p>These results look promising. We’re pretty close to BERT-large (340M parameters) performances with a much smaller model. Let’s scale things up and use RoBERTa-large instead. To do so we only need to make a few tweaks:</p><ul><li>Replace &quot;roberta-base&quot; by &quot;roberta-large&quot; in the <em>Model loading</em> code snippet (line 10)</li><li>Set batch_size to 8 in the <em>PyTorch Dataset building</em> code snippet (line 1) since the larger model will take more GPU memory</li><li>Setepochsto 3 andgrad_acc_stepsto 4 in the <em>Training and Evaluation</em> code snippet (line 1-2) in order to keep training time in check and an effective batch size of 32</li><li>Run the pipeline again</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*Or-SuqIP0InTMfZzLkJyKw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*GjEkgHiKFxsJlDMbLk025A.png" /><figcaption>RoBERTa-large results</figcaption></figure><p>Voilà ! State-of-the-art results for Yes/No Question Answering.</p><h4>Prediction</h4><p>Let’s test our model on a paragraph from the <a href="https://rajpurkar.github.io/SQuAD-explorer/">SQuAD dataset</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2308c3ba0b4eea7a67245a887f31db2f/href">https://medium.com/media/2308c3ba0b4eea7a67245a887f31db2f/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7xxFSxZhSX7dMu9s4YTmYQ.png" /><figcaption>SQuAD 2.0 example paragraph</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SAAWhR9C2I9kzNLlUA2QTA.png" /><figcaption>Predictions</figcaption></figure><p>As expected the model predicts the correct answers 🚀</p><p>To sum up, we saw that Boolean Question Answering is a difficult problem with many use cases. Through a practical guide, we fine-tuned RoBERTa on the BoolQ dataset in order to establish SOTA results.</p><h3>Next steps</h3><p>Next steps would consist in:</p><ul><li>Trying out newer models such as <a href="https://arxiv.org/abs/1909.11942">ALBERT</a> and <a href="https://github.com/google-research/electra">ELECTRA</a></li><li>Reducing inference times through <a href="https://heartbeat.fritz.ai/research-guide-model-distillation-techniques-for-deep-learning-4a100801c0eb">Knowledge Distillation</a></li><li>Combining Yes/No Question Answering with <a href="https://rajpurkar.github.io/SQuAD-explorer/">Extractive Question Answering</a></li><li>Perform <a href="https://arxiv.org/pdf/2002.09599.pdf">data augmentation</a> to increase the number of training samples</li></ul><h3>References</h3><ul><li>BoolQ paper: <a href="https://arxiv.org/abs/1905.10044">https://arxiv.org/abs/1905.10044</a></li><li>RoBERTa paper: <a href="https://arxiv.org/abs/1907.11692">https://arxiv.org/abs/1907.11692</a></li><li>BERT paper: <a href="https://arxiv.org/abs/1810.04805">https://arxiv.org/abs/1810.04805</a></li></ul><p>*Note that <a href="https://arxiv.org/abs/1910.10683">T5</a> superseded RoBERTa in the <a href="https://super.gluebenchmark.com/leaderboard">SuperGLUE leaderboard</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=223bebb70189" width="1" height="1" alt=""><hr><p><a href="https://medium.com/illuin/deep-learning-has-almost-all-the-answers-yes-no-question-answering-with-transformers-223bebb70189">Deep Learning has (almost) all the answers: Yes/No Question Answering with Transformers</a> was originally published in <a href="https://medium.com/illuin">Illuin</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a simple Open Domain Question Answering pipeline in French]]></title>
            <link>https://medium.com/illuin/building-an-open-domain-question-answering-pipeline-in-french-97304e63c369?source=rss----7e66f049dad0---4</link>
            <guid isPermaLink="false">https://medium.com/p/97304e63c369</guid>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[french]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[question-answering]]></category>
            <dc:creator><![CDATA[Manuel Faysse]]></dc:creator>
            <pubDate>Fri, 27 Mar 2020 09:23:34 GMT</pubDate>
            <atom:updated>2020-11-04T14:11:17.425Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A talking robot, metaphor of Natural Language Processing" src="https://cdn-images-1.medium.com/max/800/0*jslo3hucbXVfUPH-.jpg" /><figcaption>Image By Siarhei Tolak | Shutterstock</figcaption></figure><p><strong>Natural Language Processing</strong> (NLP) is one of the fastest growing fields of artificial intelligence. It is centered around the comprehension of human language, represented through textual data, by computers. <strong>Question Answering</strong> (QA) is a NLP subfield in which an algorithm is given a short text (a context), and is trained to answer natural questions pertaining to that text by highlighting the most relevant passage to answer the question within the context text. This approach can be generalized to Open-Domain QA (or large Close Domain QA), with the added difficulty that the context text is not given and rather has to be retrieved from a much larger set of documents by the algorithm.</p><p>While the NLP research field is extremely active, most efforts are concentrated around the English language. However, it would be false to state that no efforts are made in other languages. Recently, state-of-the-art NLP architectures were adapted to the French Language (<strong>CamemBERT</strong> and <strong>FlauBERT</strong>) and opened the way for research on a variety of tasks that were not previously possible. Specifically, Illuin Technology trained the first French Question Answering model that yields performances on par with the best English QA models.</p><p>This blog post will focus on building a simple end-to-end Open Domain Question Answering pipeline leveraging this brand new technology. The goal is not to dive into the complexities of the models that are presented, nor to build a highly optimized OpenQA model, but rather to give an overview of what exists in French NLP today and to build a simple yet useful, first of its kind, feature in French Question Answering.</p><p>The pipeline will consist in two main steps, a<strong> document retrieval </strong>step, in which a paragraph long text is retrieved from a much larger corpus, and a <strong>question answering </strong>step in which the answer to the question is highlighted from the retrieved document. In order to illustrate the process, we will use as corpus a <a href="https://ree.developpement-durable.gouv.fr/IMG/pdf/9782111570573_lenvironnementenfrance_edition2019_rapportdesynthese_v24_web_light.pdf">governmental 220 pages report discussing environment in France,</a> and will also generalize this pipeline to answer questions on the entirety of the French Wikipedia articles.</p><h3>Table Of Contents</h3><h4>Introduction</h4><h4>Document Retrieval</h4><p><strong><em>Bag Of Word</em></strong></p><p><strong><em>TF-IDF</em></strong></p><p><strong><em>Use Case: Document Retrieval</em></strong></p><h4>Question Answering</h4><p><strong><em>Word2Vec</em></strong></p><p><strong><em>FastText</em></strong></p><p><strong><em>ELMo</em></strong></p><p><strong><em>The BERT tidal wave</em></strong></p><p><strong><em>FQUAD</em></strong></p><p><strong><em>Use case: OpenDomainQA</em></strong></p><h3>Document Retrieval</h3><p>While more complex methods exist, the simplest, fastest, and most widespread information retrieval techniques are based on frequency based schemes. In 2015, over<a href="https://kops.uni-konstanz.de/handle/123456789/32348"> 83 % of text-based recommender systems were based on frequential techniques,</a> typically Wikipedia’s search engine which leveraged <strong>tf-idf </strong>weighting. All these methods are built upon the famous Bag-Of-Words method.</p><p><strong>Bag Of Words</strong></p><p>One of the simplest NLP algorithms is the<strong> Bag-Of-Words model</strong> (BOW). It consists in counting the occurences of words in a text without taking into account their order. The word frequencies can then be used as features to compare two documents, or for training downstream machine learning models, such as classifiers. This model is language independent and can be applied to any type of tests without any sort of prior training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XhMzoe6IpwBuXVipIlhA8w.jpeg" /><figcaption>Bag Of Words Representation</figcaption></figure><p>Frequency counts can be made more relevant through the use of techniques such as <strong>tokenization</strong> or <strong>stemming</strong>.</p><p>Basic <strong>tokenization</strong> is the process that aims at splitting textual data into individual words. Once each word in a text corresponds to a unique token, we can map them to a unique token id and feed them into Machine Learning algorithms. More advanced methods don’t necessarily pair each token with a single word but may rather create tokens built of a subword or at the contrary, more than one word.</p><p><strong>Stemming</strong> is the process of reducing a word to its root form. The French words “pêcher”, “pêchons” and “pêcheur” all have the same stemmed form, “pêch”. <strong>Lemmatization</strong> is a similar process that is a bit more advanced in the sense that it requires an understanding of the word and the context. The goal of lemmatization is to yield the dictionary form of a word. For example, the french verb “suis” should be lemmatized as “être”, its infinitive version. Lemmatization is a non-trivial task and no perfect algorithm exists to achieve it.</p><p>The NLTK snowball module offers stemmers based on suffix-stripping algorithms in different languages, including French, and the spaCy library, offers lemmatizers as well based on language specific lookup tables that are available for download.</p><p>In both processes, the goal is to reduce the size of the vocabulary and cluster words derived from the same roots in order to help with frequency methods, such as BOW models.</p><p><strong>TF-IDF</strong></p><p>In most texts, BOW models can be affected by very frequent words (“de”, “le” , “un” in French for example) that are not document specific and thus that do not convey relevant information to be used for retrieval or classification tasks later on. TF-IDF is a weighting formula that gives more importance to terms that are specific to a particular document. Word frequencies in a document are balanced out with the ratio of documents in which the words appear, thus helping identify the document’s specific terms and yielding a better frequential representation of a text.</p><p><strong>Use Case: Document Retrieval</strong></p><p>Now that the basic principles of Information retrieval are understood, let’s apply it to our use case. The first step is to extract textual data from the PDF report. We use Tesseract to convert the PDF report to an HTML version, then the BeautifulSoup library to split the report page by page and remove the titles, figures and captions from our corpus.</p><pre>soup = BeautifulSoup(open(&#39;data/env_fra_synthese2019.html&#39;), \<br>                     &#39;html.parser&#39;)</pre><pre>page_json = {}</pre><pre>for i,page in enumerate(re.split(&quot;Page \d+&quot;, str(soup))):<br>    <br>    tmp = []<br>    tmp_soup = BeautifulSoup(page, &#39;html.parser&#39;)<br>    <br>    for s in tmp_soup.find_all(&#39;span&#39;, {&#39;style&#39;: re.compile(r&#39;LiberationSans; font-size:9px&#39;)}):<br>        t = s.get_text()<br>        t = t.replace(&#39;\n&#39;, &#39; &#39;)<br>        if len(t) &gt; 2:<br>            tmp.append(t)<br>    <br>    page_json[i] = &quot; &quot;.join(tmp)</pre><pre>with open(&#39;data/page.json&#39;, &#39;w&#39;) as outfile:<br>    json.dump(page_json, outfile)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yrVetmJhZOHFF-CpLZrDCQ.png" /><figcaption>JSON file with the extracted PDF information</figcaption></figure><p>If we consider all pages of the original report PDF as individual documents, we can apply the TF-IDF weighting scheme to determine the most relevant lemmatized words in our document.</p><p>We use the augmented term frequency formula to prevent bias towards longer documents :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*cLLUiK5e11XcgGyKTj_OIA.png" /><figcaption>Term frequency formula. tf(t,d) corresponds to the number of occurrences of a given term t in a given document d. This tf scheme is meant to prevent bias towards longer documents by normalizing each term’s frequency with the frequency of the most frequent word.</figcaption></figure><p>Inverse document frequency is calculated as such:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*zCLPwFEQonDFBTHeHq-A0Q.png" /><figcaption>Inverse document frequency formula. N corresponds to the total number of documents in corpus D, and the fraction’s denominator is the number of corpus documents d containing term t.</figcaption></figure><p>The product of these two metrics yield the tf-idf weights of each word in each document of a given corpus.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*bKfc9kuiUMXN6FcooQFMlg.png" /><figcaption>Final tf-idf formula.</figcaption></figure><p>It is important to note that this indexing process can be lengthy but should only be done once and stored for posterior use. Observing the highest weighted term in the documents can give a pretty good idea of the discussed themes.</p><p>As an example, page 43 in the report discusses biodiversity and endangered species and the 10 highest weighted terms are ‘ours’ , ‘lynx’, ‘cantonner’, ‘pyrénéens’, ‘noyau’, ‘herbivore’, ‘prédateur’, ‘loup’, ‘comté’ and ‘intergouvernemental’. Page 94 discusses green economy and jobs, and the highest weighted terms are ‘recrutement’, ‘cdd’, ‘employeur’, ‘intention’, ‘animation’, ‘déposer’, ‘initiale’, ‘spécialement’, ‘attractif’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*o08D0BGQfD-Ya6aYBUduzg.jpeg" /><figcaption>Sidenote: Considering the entire report as a single document and using a huge corpus comprised of random Wikipedia articles yields tf-idf weights for the document that can be represented by this word cloud.</figcaption></figure><p>In order to retrieve the most relevant document from the corpus, we will retrieve the document d that maximizes the sum of the weighted terms from the query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IBFA608Ymt6PgkenOVdPsg.png" /><figcaption>D is the set of documents in the corpus, Q the set of terms of the query.</figcaption></figure><p>Let’s test our simple system out :</p><pre>question = &quot;Quelle part de communes francaises ont subit une catastrophe naturelle récemment ?&quot;</pre><pre>retrieved context =</pre><pre>&#39;Plus de quatre cinquièmes des communes françaises ont été reconnues en état de  catastrophe  naturelle   au  moins  une  fois  entre  1982  et  2015.  Cela  représente  un  cumul  de  108 900  reconnaissances de communes en état de catastrophe naturelle, dont un peu moins des trois  quarts au titre des inondations et un cinquième au titre de la sécheresse.   Le coût des différents périls couverts par le régime d’indemnisation de ces catastrophes s’élève  à environ 33 Md€ entre 1990 et 2017, soit en moyenne 983 M€ par an. Les inondations (55 %) et la sécheresse (33 %) en représentent près des neuf dixièmes.   Les  risques  technologiques  recouvrent  en  particulier  les  risques  sur  la  santé,  la  sécurité  et  l’environnement, ainsi que les risques industriels, nucléaires, chimiques, induits par les activités  humaines.   Les  sources  de  risques  technologiques  sont  notamment  :  les  installations  industrielles,  les  installations  nucléaires,  le  transport  de  matières  dangereuses,  les  sites  miniers  (on  parle  de  « l’après-mine »), les grands barrages.   Fin 2018, 18 000 communes exposées aux risques technologiques sont recensées en France.  Parmi  ces  communes,  545  (soit  3 % des  communes  à  risque)  sont  concernées  par  au  moins  trois risques technologiques, 3 434 par deux types de risques technologiques.   La moitié de ces communes sont situées dans les départements de l’Isère, du Pas-de-Calais, de  la Loire, de l’Aube, du Gard, du Rhône et des Bouches-du Rhône.&#39;</pre><p>Other more advanced options exist, such as the <strong>Okapi BM25</strong> ranking algorithm based on the same concepts.</p><p>This information retrieval step is here demonstrated on a PDF report corpus, but can easily be adapted to be used with the entirety of Wikipedia by leveraging their built-in article retrieval search engine, based partly on tf-idf weighting. This is as easy as using the Python wrapper for the MediaWiki API.</p><pre>import wikipedia<br>wikipedia.set_lang(&quot;fr&quot;)</pre><pre>question = &quot;Où est né Napoléon?&quot;<br>relevant_title = wikipedia.search(question, results=10)</pre><pre>[&#39;Jean-Christophe Napoléon&#39;,<br> &#39;Napoléon III&#39;,<br> &#39;Louis-Napoléon Bonaparte (1856-1879)&#39;,<br> &#39;Napoléon Ier&#39;,<br> &#39;Napoléon-Jérôme Bonaparte&#39;,<br> &#39;Napoléon-Louis Bonaparte (1804-1831)&#39;,<br> &#39;Victor Napoléon&#39;,<br> &#39;Villa Cyrnos&#39;,<br> &#39;Napoléon II&#39;,<br> &#39;Louis Napoléon&#39;]</pre><p>It is interesting to note that “Jean-Christophe Napoléon” is probably not the Napoléon that the user was thinking of when asking for a place of birth, and the API is very sensible to the different words present in the question. It seems the system is much more robust by first retrieving the name entities from the question (SpaCy) and querying the API without the rest of the words.</p><pre>import spacy<br>nlp = spacy.load(&#39;fr_core_news_md&#39;)</pre><pre>question = &quot;Où est né Napoléon?&quot;</pre><pre>query = &quot; &quot;.join([str(x) for x in nlp(question).ents])<br>query = query if len(query) &gt; 0 else question</pre><pre>relevant_title = wikipedia.search(query,results=10)</pre><pre>[&#39;Napoléon Ier&#39;,<br> &#39;Napoléon III&#39;,<br> &#39;Napoléon II&#39;,<br> &#39;Louis-Napoléon Bonaparte (1856-1879)&#39;,<br> &#39;Louis Napoléon&#39;,<br> &#39;Victor Napoléon&#39;,<br> &#39;Jean-Christophe Napoléon&#39;,<br> &#39;Saint-Napoléon&#39;,<br> &#39;Maison Bonaparte&#39;,<br> &#39;Le Sacre de Napoléon&#39;]</pre><h3>Question Answering</h3><p>The real beauty of this pipeline lies in the Question Answering step. QA is an ongoing research effort that has been revolutionized with the rise of embeddings and more recently Transformer networks. Understanding what led to state-of-the-art QA models today is essential to gain insight into how they work. To skip the theory and head right down to the use case, click this <a href="#fers">hyperlink</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IWr1I0MyozTMnS1G3Pq_UA.jpeg" /><figcaption>Embeddings like Word2Vec map words to a N-dimensional continuous latent space</figcaption></figure><p><strong>Word Embeddings</strong></p><p>Many of the modern NLP methods stem from <a href="https://arxiv.org/pdf/1301.3781.pdf">Mikolov’s groundbreaking research in 2013</a>. He popularized the representation of words using continuous vectors (<strong>Word2Vec</strong>) that Bengio introduced in 2001. At the time, words in NLP were usually represented by a unique index and had to be one-hot encoded to be fed into neural networks. While relying on such techniques to encode words in a given vocabulary had shown encouraging results in a variety of tasks, they led to huge and sparse representations of the input sequences, and were unable to capture similarities words may have: synonyms were as distant in their representations as any two words. Representing words as vectors in a meaningful latent space of fixed dimensionality allowed similar words to be mapped into neighboring regions of the latent space, eg. vec(“dog”) is close to vec(“puppy”). Most surprisingly, it also captured more complex relationships between objects. It was shown for example that <em>vec(“France”)-vec(“Paris) + vec(“Rome”) = vec(“Italy”)</em>. The mapping proposed is known as <em>word2vec</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*Qt8Ld2q9GWCXzm-RpIKnrw.png" /><figcaption>Equivalent relationships between words in the latent space | <a href="https://arxiv.org/pdf/1301.3781.pdf">https://arxiv.org/pdf/1301.3781.pdf</a></figcaption></figure><p>Representing words as dense vectors is usually not a goal in itself, but improves the performance of downstream tasks such as document classification, sentiment analysis, semantic understanding…</p><p>In order to construct a vectorized representation of a vocabulary, Mikolov introduced two novel strategies through the Continuous Bag-Of-Words (CBOW) model, and the Skip-Gram model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q5PcVRijAzk_OPVP" /><figcaption><a href="https://arxiv.org/pdf/1301.3781.pdf">https://arxiv.org/pdf/1301.3781.pdf</a></figcaption></figure><p>In the CBOW model, a simple neural network model is trained on predicting a word knowing the rest of the words in a context window. In the Skip-Gram model, words from the context window are predicted given the central word. In both cases, the vector representations of words from the input vocabulary are initially random, and are progressively refined during training using gradient descent methods.</p><p>These techniques do not explicitly take into account the ordering of the context words. To remedy this in an efficient manner, it is possible to create a vocabulary with tokens constructed from more than one word, known as n-grams. The idea is that n-grams partially capture word ordering and allow to leverage more information from the sequence<em>. </em>Using the CBOW or Skip-Gram models but with n-grams is shown to yield equivalent results to methods in which the word positions are explicitly defined, while being much more computationally efficient. This method is used by the <a href="https://arxiv.org/pdf/1607.01759.pdf"><strong>FastText</strong></a> algorithm, with n-grams often chosen with n=2 (bigrams). FastText, unlike word2vec, gains the ability to form good sentence representations by averaging word features and at the time, rivaled deeper neural methods while being more efficient.</p><p>Both methods can be used in any language, given they are trained with sufficient data (web crawls, Wikipedia dumps, etc.)</p><h3>Contextualized representations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iil-cBoHgxsRGfZ8e-LV_g.jpeg" /><figcaption>In NLP, context matters !</figcaption></figure><p><strong>ELMo</strong></p><p>Up to now, we have only talked about pre-trained word representations that do not depend on the context of the word or the n-gram in the sentence context. The word “bank” for example would have the same vector representation whether it was used in the sentences “I put money in the bank” and “we hiked along the river bank”. The Allen Institute for Artificial Intelligence published a paper, “<a href="https://arxiv.org/pdf/1802.05365.pdf">Deep contextualized word representations</a>” in 2018 meaning to change this. In their proposed representation, each word token is assigned a representation that depends on the entire surrounding sentence. Although the idea had already been explored in previous works, their proposed architecture, ELMo, that leveraged biLMs, bidirectional deep LSTM models trained with Language Model objectives (next word prediction) achieved state-of-the-art results in a variety of downstream NLP tasks. It was shown that depending on the depth of the internal LSTM states, different language features were captured; higher level states understood a word in its context, while lower level could model the syntax. To combine all these features, ELMo’s final vector representation of a word in its context is a linear combination of the representations from the top layers of the biLMs as well as the intermediate representations coming from the hidden internal layers. ELMo vectors are meant to be used as additional features that can be added to existing models to improve their performance. A French version of the ELMo model trained on Wikipedia dumps and Common Crawl data can be found at <a href="https://github.com/HIT-SCIR/ELMoForManyLangs">https://github.com/HIT-SCIR/ELMoForManyLangs</a>.</p><p><strong>Going Deeper: Transformers</strong></p><p>In the ELMo architecture, LSTMs are the backbone required to learn contextualized representations of words. In December 2017, the paper “<a href="https://arxiv.org/pdf/1706.03762.pdf">Attention is all you need</a>” introduced the concepts of transformer networks. Transformer networks are encoder-decoder networks that rely on self-attention mechanisms to help the model focus on the most relevant words in the context. For every word in the input sequences, self attention determines the most relevant context words, which are then given more importance upon encoding the contextualized word vectors. This allows models to learn long term dependencies in the input sequences that recurrent neural networks like LSTMs or Gated Recurrent Networks were not able to do. The authors show that the attention mechanism is sufficient in itself and there is no need to add recurrent connections or convolutions to the models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/0*9xkLbgBc-7ff6ofp.png" /><figcaption>The word “it” is linked with some words more than others | <a href="http://jalammar.github.io/illustrated-transformer/">http://jalammar.github.io/illustrated-transformer/</a></figcaption></figure><p>In transformer networks, a sequence of words is thus translated into a context-dependent sequence of vectors in the encoder. These vectors are later used by the decoder to generate an output sequence word by word. Words that are generated depend on the encoder output, as well as on the previously generated words through attention mechanisms. Transformers were immediate breakthroughs in sequence to sequence tasks such as Machine Translation.</p><p><strong>The BERT tidal wave</strong></p><p>The <a href="https://arxiv.org/pdf/1810.04805.pdf">BERT</a> (Bidirectional Encoder Representations from Transformers) model, released by Jacob Devlin’s team in 2018 is based on transformer encoders. BERT is a framework that is meant to be used in two steps; first pre-training the transformer encoder backbone on unlabeled textual data, then modifying the model by adding an additional output layer and fine-tuning it on task-specific data. The costly pre-training process is a one-time effort, and the model can then be easily trained on a variety of downstream tasks, thus generalizing the transfer learning process, frequent in computer vision, to NLP tasks.</p><p>In the backbone, input tokens are split using an algorithm called “WordPiece” and the wordpiece embeddings are learned during the training process. WordPiece reduces the vocabulary size by splitting infrequent words in subwords or even individual characters, while frequent words keep their integrity. These embeddings are then transcribed through feed-forward and attention layers into unique contextualized vector representations. The specificity that BERT introduces mostly lies in the pre-training process. BERT, as the title suggests, generates its representations by training a language model that generates its predictions by leveraging information from tokens before and after the token the model aims to predict. This is achieved by randomly masking WordPiece tokens and training the model to predict the identity of the masked tokens (Masked Language Model). The authors show that using bi-directional inputs is an improvement upon similar models that only relied on unidirectional language models (OpenAI GPT). An additional training objective of the BERT model is to predict whether a pair of sentences follow each other in the original text or not (Next Sentence Prediction).</p><p>Once pre-trained, the model can then be slightly modified by adding an additional output layer and fine-tuned on a specific task. This simple step allows BERT to achieve state-of-the-art results in a variety of tasks such as question-answering (QA), paragraph continuation (SWAG), Natural Language Inference (NLI), sentiment analysis, semantic equivalence (MRPC, QQP).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f3rKTFjUOtchqjr5VHIUFw.png" /><figcaption>Fine-tuning and Pre-training procedures for BERT model. For QA fine-tuning, the only difference is that a Start and End vector are introduced to predict the span of the answer in the original paragraph. | <a href="https://arxiv.org/pdf/1810.04805.pdf">https://arxiv.org/pdf/1810.04805.pdf</a></figcaption></figure><p><strong>Upgrading BERT</strong></p><p>The <a href="https://arxiv.org/pdf/1907.11692.pdf"><strong>RoBERTa</strong></a> model improves upon BERT by tweaking the training hyper-parameters and using larger mini-batches, relying on dynamic masks that are generated each time a sequence is fed to the model, removing the Next Sentence Prediction task they show to be detrimental and training on full sentences. It relies on a Byte-Pair Encoding BPE instead of the original WordPiece tokenizer choice.</p><p>The <a href="https://arxiv.org/pdf/1910.01108.pdf"><strong>DistilBERT</strong></a> model mainly aims to reduce the model size to improve inference speed and allow the model to be used on devices with limited computing capacities. It is trained using knowledge distillation, a technique in which a smaller “student” network aims to reproduce the behavior of a bigger “parent” network. The authors show they are able to reproduce 99% of the performance capacities with a much smaller model.</p><p>The authors from the <a href="https://arxiv.org/pdf/1909.11942.pdf"><strong>ALBERT</strong></a> model observed that bigger models often led to better results. In order to scale up the BERT model without an explosion of the number of parameters, they aim to improve the efficiency of the BERT architecture by leveraging weight sharing between layers and by using matrix factorization on the embedding parameters to reduce their number. Reducing the number of parameters as such (18x decrease) allows the ALBERT model to imitate BERT models that would be much deeper with a similar number of parameters. Finally, the Next Sentence Prediction task is replaced by a sentence ordering problem (SOP) in which the goal is to determine the original ordering of two consecutive sentences in the original document.</p><p><strong>CamemBERT</strong></p><p><a href="https://arxiv.org/pdf/1911.03894.pdf">CamemBERT</a> is a French version of the RoBERTa model. It differs slightly with its use of whole word masking (as opposed to subword token masking in the original model), and a SentencePiece tokenizer, extension of the WordPiece concept. It is trained on web data from the OSCAR dataset a filtered version of the French Common Crawl corpus. The French OSCAR dataset that was used amounts to over 138 GB of textual data. CamemBERT is the first effort to adapt the BERT model family in French, and provides baselines for a variety of NLP tasks. The model and loading code are available at <a href="https://camembert-model.fr/">https://camembert-model.fr/</a>, in TorchHub, as well as in the HuggingFace transformer library <a href="https://github.com/huggingface/transformers">https://github.com/huggingface/transformers</a>.</p><p><strong>FlauBERT</strong></p><p><a href="https://arxiv.org/pdf/1912.05372.pdf">FlauBERT</a> is a another parallel, government subsidized, effort to adapt BERT to the French language. It is similar in all points to the RoBERTa model, apart from a pre-processing step to tokenize full words that is specific to French before using the BPE encoding process. It is trained on a variety of French sub-corpus ranging from web crawls to written books. It is interesting to note that the training data amounts to 71 GB of data, about half of what was used for the CamemBERT pretraining. The model and code are available at <a href="https://github.com/getalp/Flaubert">https://github.com/getalp/Flaubert</a> and a HuggingFace implementation of the model exists as well.</p><p><strong>FQuAD</strong></p><p>Two barriers prevented the development of efficient Question Answering models in French until recently. The first was the lack of state-of-the-art transformer networks pre-trained specifically on a French Corpus. The second was the lack of an annotated, quality dataset in French comprised of sets of Context-Questions-Answers necessary to fine-tune a pretrained model. The first barrier fell in late 2019 with the release of CamemBERT and FlauBERT, while the second barrier has been shattered just a few months later in February 2020 with the open release of <a href="https://fquad.illuin.tech/"><strong>FQuAD</strong></a>, the French equivalent of SQuAD, a dataset with thousands of human annotated questions and answer pairs pertaining to Wikipedia contexts.</p><p>Training a model became possible,and by finetuning the CamemBERT model, the authors from the FQuAD paper set a new baseline for efficient Question Answering models in the French language. A demonstration platform is available at <a href="https://fquad-demo.illuin.tech/">https://fquad-demo.illuin.tech/</a>.</p><p><strong>Use case: Question Answering on the retrieved context</strong></p><p>Using our document retrieval system, we can feed the question and the retrieved context to the Question Answering model finetuned on <strong>FQuAD</strong>.</p><p>First, we install the dependencies. The FQuAD pretrained model architecture is built on top of the CamemBERT model in the Hugging Face transformers library, itself built on top of the RoBERTa Hugging Face implementation.</p><pre>import torch<br>from transformers.modeling_camembert import CamembertForQuestionAnswering<br>from transformers import CamembertTokenizer</pre><p>We can now define a QA model class by using the CamembertQA model architecture available on Hugging Face. Tokenizers are language specific so we download the CamemBERT tokenizer, and the model weights from Illuin Technology’s QA model on Hugging Face.</p><pre>model_path = &#39;illuin/camembert-base-fquad&#39;</pre><pre>tokenizer = CamembertTokenizer.from_pretrained(model_path)<br>model   = CamembertForQuestionAnswering.from_pretrained(model_path)</pre><p>The only thing left to do is to run the model with a question and context and retrieve the answer text from the tokenized input using model predictions on the most probable start and end logits.</p><pre>def evaluate(question,text):<br>  input_ids = tokenizer.encode(question, text)<br>  start_scores, end_scores = model(torch.tensor([input_ids]))<br>  all_tokens = tokenizer.convert_ids_to_tokens(input_ids)</pre><pre>  start = torch.argmax(start_scores)<br>  end = torch.argmax(end_scores)+1</pre><pre>  return &#39;&#39;.join(all_tokens[start:end]).replace(&#39;▁&#39;,&#39; &#39;).strip()</pre><p>The presented version of the code doesn’t scale to larger input sequences (512 tokens maximum between the text and the question) and only allows the retrieval of the most probable answer. To implement a robust version of the pipeline, it is recommended to use the <em>evaluate</em>() function <a href="https://github.com/huggingface/transformers/blob/master/examples/run_squad.py">(https://github.com/huggingface/transformers/blob/master/examples/run_squad.py</a>) provided in the SQuAD examples of the Hugging Face repository.</p><p>Let’s try the full pipeline with a question that the report contains the answer to.</p><pre>question = &quot;Quels facteurs influent sur l&#39;espérance de vie à la naissance ?&quot;</pre><p>First, a context is retrieved using a BOW technique with TF-IDF weighting. The model correctly identifies the page with the anwer to be page 172.</p><pre>Ainsi, 12 % des adultes vivent dans un foyer en situation d’insécurité alimentaire pour raisons  financières. Ces personnes sont plus jeunes que les autres et en majorité des femmes. Malgré  un revenu supérieur en moyenne au seuil de pauvreté, elles semblent devoir plus souvent faire  face seules à des dépenses élevées, notamment pour le logement, mais aussi à des contraintes  importantes en termes d’accès aux soins et à l’alimentation .   L’état de santé des populations marqué par la situation économique   L’espérance de vie à la naissance représente la durée de vie moyenne d’une génération fictive  soumise  aux  conditions  de  mortalité  de  l’année.  Elle  intègre  les  conséquences  de  divers  facteurs : mortalité prématurée, qualité de l’offre de soins (accès aux soins, densité médicale),   comportements à risque, etc. La structure des emplois constitue également un déterminant.   La situation économique des ménages est un facteur susceptible de limiter, voire d’empêcher,  l’accès  aux  soins.  Le  taux  de  renoncement  aux  soins  pour  des  raisons  financières  permet  d’estimer la part de la population concernée par ces barrières. En 2014, 2,3 % de la population  (soit  environ  1,5 million  de  personnes)  déclare  avoir  renoncé  à  des  soins  pour  des  raisons  financières  au  cours  des  douze  derniers  mois  (Insee,  SRCV-Silc).  Depuis  2010,  cette  part  augmente peu à peu (+ 0,6 point sur la période observée).   Selon l’enquête SRCV (Insee), en 2016, 1,4 % des ménages pauvres ne disposent pas d’une  douche ou  d’une  baignoire  (contre  0,6 % dans  le  reste  de  la  population).  1,1 % des  ménages  pauvres  n’ont  pas  d’eau  chaude  (0,4 %  chez  les  autres).  8,8 %  des  ménages  pauvres  ne  possèdent pas de système de chauffage central ou électrique (3,7 % chez les autres). De plus,  la surface moyenne du logement est 62 % plus importante chez les propriétaires que chez les  locataires (Insee, enquête Logement 2013).   L’enquête  SRCV  2016  révèle  aussi  que  920 000  ménages  vivent  dans  des  logements  composés  d’une  seule  pièce.  38 %  de  ces  ménages  sont  en  situation  de  pauvreté.  Plus  de  60 000 enfants vivent avec leur famille dans une seule pièce.</pre><p>The QA model can then run given the question and the context and retrieve the correct answer.</p><pre>Answer: &quot;mortalité prématurée, qualité de l’offre de soins (accès aux soins, densité médicale), comportements à risque&quot;</pre><p>This method’s bottleneck lies in the information retrieval step and queries that are syntaxically too different from the text contained in the corpus documents will not yield great results.</p><p>As previously stated, the same technique can be generalized to information retrieval on the Wikipedia platform. The same bottleneck exists, as the information retrieval step is highly dependant on the Wikipedia search engine, based on weighted frequency methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wrXJy9RagebGwmRUV4vzkQ.png" /><figcaption>Open-domain Question Answering search engine built with the previously detailed pipeline</figcaption></figure><h3><strong>Conclusion</strong></h3><p>While the pipeline is relatively simple, the model manages to perform fairly well on a diverse range of open questions. Improvements in the retrieving steps could go a long way in creating a more robust model, but steps could also be taken in the question answering stage to answer giving more realistic confidence intervals. Running the pipeline over the n-best retrieved documents and reranking the answers based on the combined score of the retrieving step and the confidence score given by the question-answering model could also help improve the accuracy of the pipeline. Using a question answering model trained with questions that have no answer in the given context (SQuAD2) could also help determine that the retrieved document was incorrect and help improve robustness. Work is underway in this direction.</p><p>It is easy to imagine the industrial applications of such a pipeline and a more complex version could easily be used to precisely query large information databases, user manuals, websites…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*nRmlW_1JQswlKaKETHLscA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*qIymc4QuFduP5ek2AW8dIQ.png" /><figcaption>Open-Domain QA pipeline could be integrated into chatbots for diverse uses</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97304e63c369" width="1" height="1" alt=""><hr><p><a href="https://medium.com/illuin/building-an-open-domain-question-answering-pipeline-in-french-97304e63c369">Building a simple Open Domain Question Answering pipeline in French</a> was originally published in <a href="https://medium.com/illuin">Illuin</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FQuAD: French Question Answering Dataset]]></title>
            <link>https://medium.com/illuin/fquad-97d53c925bd3?source=rss----7e66f049dad0---4</link>
            <guid isPermaLink="false">https://medium.com/p/97d53c925bd3</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[question-answering]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Wacim Belblidia]]></dc:creator>
            <pubDate>Wed, 04 Mar 2020 10:09:07 GMT</pubDate>
            <atom:updated>2020-03-04T10:09:07.211Z</atom:updated>
            <content:encoded><![CDATA[<h4>To stimulate French AI: the first native French QA Dataset</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*sGcqwY_Ha-8tDCc0vQx4hA.png" /></figure><p>Today, we introduce <a href="https://arxiv.org/pdf/2002.06071.pdf">FQuAD</a>, the first native French Question Answering Dataset. We finetuned the CamemBERT Language Model on the QA task with our dataset, and obtained 88% F1. To see it in action, check out <a href="https://fquad-demo.illuin.tech/">our trained QA model</a> !</p><h4>Table of Contents</h4><ol><li><strong>Introduction</strong></li><li><strong>Dataset Collection</strong></li><li><strong>Dataset Analysis</strong></li><li><strong>Experiments</strong></li><li><strong>Test it yourself !</strong></li></ol><h3>Introduction</h3><h4>Question Answering</h4><p>As the name indicates, the task of Question Answering (QA) consists of finding an <em>answer </em>in a particular text given a specific <em>question</em>.</p><figure><a href="https://en.wikipedia.org/wiki/2018_FIFA_World_Cup"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7WnxQ5SbjlophvYl1B1cEg.png" /></a></figure><p>Recent advances in NLP have improved the state-of-the-art on this task, with the models being trained &amp; evaluated on datasets such as <a href="https://rajpurkar.github.io/SQuAD-explorer/">SQuAD</a>. However, these models being very much language dependent, and the datasets being almost solely available in English, French QA has not seen the same growth as its English counterpart.</p><h4>Extension to French (and other languages)</h4><p>English QA datasets are <strong>big </strong>(100,000+ questions). Current low-resource approaches to create datasets in other languages include translating the English ones to the desired language, translating text and question to English during the prediction, or using a multilingual language model. However, none of these options get quite the same results as native crowd-sourced <em>language specific </em>datasets.</p><h3>Dataset Collection</h3><p><strong>Paragraph Collection</strong></p><p>In this work, we chose the latter option, and created a crowd-sourced French QA Dataset of more than 25,000 questions. Following <a href="https://rajpurkar.github.io/SQuAD-explorer/">SQuAD</a>’s approach, we randomly sampled 145 articles from <a href="https://fr.wikipedia.org/wiki/Cat%C3%A9gorie:%20Article_de_qualit%C3%A9">Wikipedia’s French quality articles</a>, further split into paragraphs.</p><p><strong>Question &amp; Answer Collection</strong></p><p>With our own annotation platform, crowd-workers were asked to create 3–5 question-answer pairs per paragraph</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zGMh8svF4JyUBrLA98OOJA.png" /><figcaption>ILLUIN Technology’s QA Annotation Platform</figcaption></figure><p>This is where the current dataset stands (it’s being extended):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zYtStEuZwrgCEuIYQu-n-w.png" /></figure><h4>Additional answers collection</h4><p>Human annotators may not all select the exact same text span when choosing the answer.</p><blockquote><strong>Quand fut couronné Napoléon ?</strong></blockquote><blockquote><em>Possible selected answers in the text: </em>mai 1804, en mai 1804, 1804</blockquote><p>In order to decrease this annotation uncertainty, for the test set (dev set underway), we provided the crowd-workers with already created questions, and asked them to find the corresponding answer. This way, all test set samples have 3 answers from different annotators.</p><h4>Some examples from the dataset</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*NNwNKZX0bm-snjNbTVVJrw.png" /></figure><h3>Dataset Analysis</h3><p>We collected a diverse collection of questions and answers, which makes for robust QA models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b9rOfThFTdvMQxv4TELSLQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z4DBBcXrNGk_D2dgUqwoKQ.png" /><figcaption>Question/Answer type frequency in FQuAD</figcaption></figure><p>The crowd-workers were encouraged to ask difficult questions, and it shows in the dataset. <em>Difficult </em>implies linguistic variations between the question and its corresponding answer. This can mean using synonyms, changing the syntax, requiring world knowledge or information over multiple sentences to answer the question.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JtE1H8HzVUksQQ7sH_LnZA.png" /><figcaption>Question-answer relationships in 108 randomly selected samples from the FQuAD development set. In bold the elements needed for the corresponding reasoning, in italics the selected answer.</figcaption></figure><h3>Experiments</h3><p>With the dataset now constituted, the goal was to finetune a Language Model on the QA task. Thanks to the recently released French Language Models, <a href="https://arxiv.org/pdf/1911.03894.pdf">CamemBERT</a> and <a href="https://arxiv.org/pdf/1912.05372.pdf">FlauBERT</a>, the process of creating such models becomes straightforward with the <a href="https://github.com/huggingface/transformers">HuggingFace library</a>.</p><h4>Results</h4><p>We fine-tuned the Language Models on FQuAD, as well as a translated version of SQuAD and a combination of the two.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VJ6EF_a9wPnQVzGFoTaSCg.png" /><figcaption>Test scores of different models trained and evaluated on FQuAD (ours) and SQuAD translated</figcaption></figure><p>Our best model, CamemBERTQA, reaches a performance of <strong>88.0% </strong>F1 and <strong>77.9%</strong> EM on the FQuAD test dataset. Interestingly, we can see a strong bias between translated and native french data, reflected in the scores on the respective test sets depending on which training set was used.</p><h4>Performance Analysis</h4><p>If we look at how the model performs on the different question &amp; answer types, we see that it works best on structured data likes <em>numbers</em> or <em>proper nouns, </em>but still manages to produce adequate results on more complex types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z-oMgE8ZkDDlVV2J0QFmBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RGNoObVAkDtOkwdGK9dj2g.png" /><figcaption>Performance on question/answer types. F1h and EMh are the human scores</figcaption></figure><h4>Learning Curve</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TxqpMPRm7mhTpQu5A5vYCQ.png" /><figcaption>CamemBERTQA’s learning curve with subsets of FQuAD</figcaption></figure><p>In order to better understand how the number of samples affected the model’s performance, we carried multiple runs with subsets of different training sizes, and evaluated on the same test set. As more samples are added, performance improves.</p><p>The dataset is growing as I’m writing this article, and we’ll also soon publish an updated baseline with state-of-the-art multilingual models as a comparison. Stay tuned for updates !</p><h3>Test it yourself!</h3><p>You can <a href="https://fquad.illuin.tech/">download</a> the dataset, and check out our trained QA model <a href="https://fquad-demo.illuin.tech/">demo</a> :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97d53c925bd3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/illuin/fquad-97d53c925bd3">FQuAD: French Question Answering Dataset</a> was originally published in <a href="https://medium.com/illuin">Illuin</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unsupervised Question Answering]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/illuin/unsupervised-question-answering-4758e5f2be9b?source=rss----7e66f049dad0---4"><img src="https://cdn-images-1.medium.com/max/1200/1*qXDx8_zS2BBVj0S9iN613Q.jpeg" width="1200"></a></p><p class="medium-feed-snippet">How to train a model to answer questions when you have no annotated data</p><p class="medium-feed-link"><a href="https://medium.com/illuin/unsupervised-question-answering-4758e5f2be9b?source=rss----7e66f049dad0---4">Continue reading on Illuin »</a></p></div>]]></description>
            <link>https://medium.com/illuin/unsupervised-question-answering-4758e5f2be9b?source=rss----7e66f049dad0---4</link>
            <guid isPermaLink="false">https://medium.com/p/4758e5f2be9b</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[question-answering]]></category>
            <dc:creator><![CDATA[Kayo Yin]]></dc:creator>
            <pubDate>Thu, 17 Oct 2019 18:24:08 GMT</pubDate>
            <atom:updated>2019-10-17T18:24:08.342Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Named Entity Recognition with BiLSTM-CNNs]]></title>
            <link>https://medium.com/illuin/named-entity-recognition-with-bilstm-cnns-632ba83d3d41?source=rss----7e66f049dad0---4</link>
            <guid isPermaLink="false">https://medium.com/p/632ba83d3d41</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[named-entity-recognition]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[recurrent-neural-network]]></category>
            <dc:creator><![CDATA[Wacim Belblidia]]></dc:creator>
            <pubDate>Tue, 20 Aug 2019 09:02:49 GMT</pubDate>
            <atom:updated>2019-08-20T09:45:28.361Z</atom:updated>
            <content:encoded><![CDATA[<h4>Extracting information from unstructured document</h4><h4>Deep Learning based entity extraction</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N9f2WoEJ0t3W6Vz6U89EBQ.jpeg" /></figure><h3>Introduction</h3><p>Among the wide range of Natural Language Processing tasks, Named Entity Recognition (NER) has always been focusing a strong stream of research works. Named Entity Recognition consists in extracting structured pieces of information such as a Name, a Location, a Company, a University name, an Activity sector, etc. from chunks of unstructured text.</p><p>Business and industry applications are numerous: extracting relevant information from resumes (Names, Skills, College, Hobbies), speeding up document processing in CRMs, building company profiles based on annual reports, etc. Most advanced chatbots often integrate NER pipelines in their AI engines.</p><p>From simple regular expressions to cutting-edge Deep Learning implementations, this task can be tackled with various levels of complexity. For instance, the 1.0 NER algorithm simply consist in using a dictionary of known terms to search and extract the matching occurrences.</p><p>This article presents the implementation and training of a model inspired from a former state of the art model for Named Entity Recognition : Chiu &amp; Nicols, <em>Named Entity Recognition with Bidirectional LSTM-CNNs</em>, 2016.</p><p>To tackle this challenge, we used a set of annotated documents, issued from public annual reports of large companies. The goal is to find 4 types of entities in these documents:</p><ul><li>Locations <em>(countries, cities, districts, addresses, etc.)</em></li><li>Company names</li><li>Group names</li><li>Activity sectors.</li></ul><p>Below is an example of a training sample, with its ground truth entities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Rbz6kheJAV3kLKbxOilvg.png" /><figcaption>One sentence with its extracted entities</figcaption></figure><h3>Data</h3><h4>Raw data</h4><p>We used a dataset with 89 public annual reports. These reports represent approximately 54,000 sentences. Entity occurrences are detailed below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Qw4934PN8Ls1BCaWz59ig.png" /></figure><p>As most NLP applications, textual data is processed by reading its words sequence. Learning the NER extraction on the whole document would be inefficient, as the sequence would be extremely long (thousands of words). Hence, each sentence is processed separately, so that our dataset contains 54,000 samples. This choice won’t change the model learning capabilities, because the context needed to understand an entity is often limited to the sentence itself.</p><p>Moreover, treating the sentences independently brings a better generalisation capability: sentences from different documents will be mixed up and gathered into same learning batches.</p><p>This large dataset is split into a training set <em>(70%), </em>a validation set <em>(20%) </em>and a test set <em>(10%).</em></p><h4>Features</h4><p>The model we implemented extracts information using 4 word-wise learning features :</p><ul><li><strong>Feature 1: The word.</strong> That’s the common way to tackle NLP challenges. Words are preprocessed and mapped to their id in a vocabulary. Words are then embedded as continuous vectors.</li></ul><pre>[&quot;One&quot;, &quot;sentence&quot;, &quot;with&quot;, &quot;5&quot;, &quot;WORDS&quot;]</pre><ul><li><strong>Feature 2: The word’s text case.</strong> We extract the case information from each word : <em>lowercase, uppercase, titlecase, numeric, partially_numeric, etc</em>. This feature is useful as some entities are highly correlated to case information. For instance acronyms will be uppercase and are unlikely to carry an <em>activity sector</em> information, while <em>company</em> names are likely to be titlecase.</li></ul><pre>[titlecase, lowercase, lowercase, numeric, uppercase]</pre><ul><li><strong>Feature 3: The word&#39;s Part-Of-Speech tag.</strong> Grammatical data definitely helps getting information on the entities : for instance, a <em>company</em> name is very unlikely to be a verb, an <em>activity</em> sector might be mainly common names, etc. We used the NLTK library to extract these information</li></ul><pre>[CardinalDigit, Noun, Preposition, CardinalDigit, Noun plural]</pre><ul><li><strong>Feature 4 : The word&#39;s characters.</strong> Each word is processed as the sequence of its characters. This is helpful to understand natural language patterns: for instance, common language patterns might be more frequent in <em>activity sectors</em> than in <em>location</em> names. Moreover, this allow a better generalisation for OOV (<em>Out-Of-Vocabulary</em>) words, as we can still extract information from their chars.</li></ul><pre>[[O,n,e], [s,e,n,t,e,n,c,e], [w,i,t,h], [5], [W,O,R,D,S]]</pre><p>Each of these features is a sequence element : each word of the origin sentence maps a time step in the 4 features. Thus, one training sample will be represented as 4 sequences of features.</p><h4>Labels</h4><p>The NER task aims at predicting an entity type for each word of the sentence. Each token can be assigned to either the <em>O</em> category (the word is not an entity we are looking for), or one of the four entity types : <em>Location</em>, <em>Group</em>, <em>Company, Activity</em>. One label is then simply a sequence of tags, such as this one :</p><pre>[O, O, O, Company, O, Group, O, O, O, Location, Location, Location]</pre><h4>Preprocessing</h4><p>Some preprocessing operations are applied to clean an normalize the text inputs:</p><ul><li>After extracting the case information for the feature 2, the text is <em>lowercased</em> for creating the embedding representations</li><li>Tokenization : We used the <em>WordPunktTokenizer</em> function of NLTK.</li><li>DIGIT : An important amount of tokens are numeric, such as dates or amounts. In order to reduce the size of the vocabulary, an usual preprocessing operation consists in replacing digit characters by the special token “&lt;DIGIT&gt;”. For instance, the year “2019” will be replaced by “&lt;DIGIT &gt;&lt;DIGIT &gt;&lt;DIGIT &gt;&lt;DIGIT &gt;”. This way, we extract only the formatting information from these tokens, not the value. This operation reduced the amount of numeric tokens from 11,000 to only 1,000 tokens.</li></ul><p>We didn&#39;t remove stop words, because they can be critical for understanding entities in a sentence : for example, <em>locations</em> are very likely to be preceded by a preposition such as &quot;in&quot;, &quot;to&quot;, etc.</p><p>What&#39;s more, we didn&#39;t apply lemmatisation and stemming processes as they might cut sensitive information.</p><p>To wrap-up, below is an overview of 5 training samples as they are fed in the network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P_hplrpgiqEvDTBMLok3_g.png" /><figcaption>Training samples after feature engineering and preprocessing</figcaption></figure><h4>Filtering</h4><p>After a few rounds of trainings, we also decided to filter out some samples according to the following criteria:</p><ul><li>Too long sentences, that brings both learning and memory challenges (too long sentences will require important volumes of padding in the tensors)</li><li>Some &quot;empty&quot; sentences that don&#39;t contain any entity. 51% of the sentences (<em>~28,000 sentences</em>) contains only &quot;O&quot; tags. Although teaching the model to recognize empty sentences is important, the 51% proportion might unbalance the training phase. Hence, 80% of the empty sentences <strong>of the training set </strong>are dropped.</li></ul><h4>Vocabulary management</h4><p>Correctly managing the size of our vocabulary is crucial, as it highly correlates with the number of trainable weights. Embedding weights are a major part of the network’s training effort. Three strategies can be applied to choose a vocabulary:</p><ul><li><strong>Building a vocabulary from the training set documents.</strong></li></ul><p>Approximately 33,000 tokens compose the training set. This vocabulary might be cut to a lower size: removing unfrequent words from the vocabulary ensures a better generalisation capability, because the model will get used to see unknown words. Hence OOV words are replaced by the special token &lt;<em>UNKOWN</em>&gt;. This token, as the other words, has a representation to be learnt in the embedding matrix.</p><p>This method handles perfectly the dataset specifics, but might be stuck at inference phase with OOV words.</p><ul><li><strong>Using a ready-to-use vocabulary.</strong></li></ul><p>When using pre-trained embeddings, common word vocabularies are available. As for the previous method, a maximum vocabulary size can be defined to have a sufficient volume of OOV words in the training corpus. This method generalizes quite well to unknown texts, as most common words might have a representation. However, the corpus specifics are uncovered, for instance the DIGIT-based words carrying information about percentages, dates, etc.</p><ul><li><strong>Hybrid method combining pre-trained and custom vocabulary</strong></li></ul><p><em>This is the approach we developed</em>. In order to take advantage of both methods, we built a hybrid vocabulary from the pre-trained <em>GloVe </em>vocabulary and our dataset words. <em>GloVe</em> words ensure a generic language comprehension of the texts, while the corpus specific words bring some specifics about the corpus nature, for instance for DIGIT-based tokens, acronyms, some specific vocabulary designating companies (e.g. <em>Company XYZ </em><strong><em>Ltd</em></strong><em>.).</em></p><p>The way we crossed these two vocabularies is illustrated below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7PMMlkpsqMAyWjd568eGqA.png" /><figcaption>Hybrid vocabulary building method</figcaption></figure><h3>Modeling</h3><p>The following elements detail an implementation inspired from Chiu &amp; Nicols, <em>Named Entity Recognition with Bidirectional LSTM-CNNs</em>, 2016 network. The architecture&#39;s overview is detailed below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mbkh_9kLbJ3jjKKAEmrBbA.png" /><figcaption>Architecture overview of Chiu &amp; Nicols network.</figcaption></figure><h4>Features Embedding</h4><p>The sample features are first embedded into a continuous space (<em>Embedding </em>layers). Except for the character-wise feature, the input data is a sequence of ids representing indexes for a look-up operation. Each timestep of these sequences is represented as a continuous vector. These continous vectors are stored in embedding matrices, whose weights are trainable.</p><ul><li>For words <em>(feature 1)</em>, we use the <em>GloVe</em> Embedding (dimension 50) as pre-trained weights for the 30k <em>GloVe </em>words. For the 5k specific words, a random vector is initialized by sampling a uniform distribution. All the vectors are trainable, and will be updated during training. The final embedding matrix hence contains 35,000 vectors of dimension 50.</li><li>For the casing and POS inputs <em>(features 2 &amp; 3)</em>, possible values are very limited: there are 5 possible casing for the words, and 30-ish POS tags in the NLTK package. These values are still represented as continuous vectors in embedding spaces. We used <em>3 dimensions</em> for the casing input, and <em>5 dimensions </em>for the POS embedding. This process replaces the common <em>One-Hot-Encoding </em>process for categorical features, by bringing more understanding to the feature&#39;s values.</li></ul><h4>Char CNN</h4><p>Last but not least, the character-wise input <em>(feature 4) </em>requires a specific treatment. Indeed, as sentences are represented through 2 nested sequences (words &amp; chars), they cannot be embedded easily.</p><p>In order to compute a continuous representation of the same nature, a CNN is applied: each character is embedded in a character embedding matrix, of <em>dimension 10</em>. Then, a <em>1D Convolution</em> layer processes the sequence of embedded char vectors, followed by a <em>MaxPooling</em> operation. This way, each word gets a vector representation (whatever its length).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9qWgTu0_mimDMog1LniUoQ.png" /><figcaption>Char-CNN process, e.g. on the world “HEALTH”</figcaption></figure><p>Of course, both the character embedding weights and the CNN filters are trainable. We set up filters of width 3: an odd number helps keeping some symmetry in the chars pattern research.</p><h4>Concatenate</h4><p>Finally, the 4 continuous representations are concatenated so that each timestep is represented with one vector, of size:</p><p>50 <em>(feature 1)</em>+ 3 <em>(feature 2)</em>+ 5 <em>(feature 3)</em> + 10 <em>(feature 4)</em> = 68</p><p>Training samples are hence fed to the recurrent layer as a tensor of shape <em>(sentence_length, 68)</em>.</p><h4>Bi-LSTM</h4><p>The training sample is now represented by a sequence of vectors. A bidirectional LSTM network <em>(dimension 275) </em>is applied on this sequence of vectors. As the label is a sequence of tags, we keep as output each LSTM cell’s hidden state. 2 LSTM layers are used.</p><h4>Dense Layer</h4><p>At each timestep, a Dense layer <em>(32 units) </em>extracts information from the LSTM hidden states. Weights are shared across timesteps. A Softmax activation over the 5 possible NER tags computes the final probability distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yh5B-os3RsAZ8s18PZ3k2A.png" /><figcaption>One training sample fully represented. 4 embedded features, along with the labels sequence.</figcaption></figure><h3>Training</h3><h4>Batch generation</h4><p>Training this model requires some adjustments on the batch generation process.</p><p>First, to avoid having too much disparity in the sentence lengths in batches, sentences are <em>bucketed</em> by length (<a href="https://arxiv.org/pdf/1708.05604.pdf">Khomenko et. al., 2017</a>). The idea is to gather sentences of similar length in the same batch, to avoid having inefficient padding values.</p><p>Second, the feature sequences need to be stacked, so that only one tensor enters the first layer. The char feature has an additional tensor depth: the Keras input layer is fed with two separate inputs to avoid useless depths on the features 1, 2 and 3.</p><p>Moreover, in order to further improve network’s generalization, <em>UNKNOWN </em>tokens are randomly used as a replacement to sentence words. The idea is to get the model to regularly see unknown words and take advantage of surrounding context.</p><h4>Loss function</h4><p>An averaged categorical cross entropy is used: at each timestep, a categorical cross entropy value is computed. The values are then averaged to get rid of the sequence length, otherwise long sentences would have much higher costs that short sentences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tReOfUrV8SzReRnw0do_bQ.png" /><figcaption>Training loss function. The k outputs correspond to the 5 entity tags : Location, Company, Group, Activity, O</figcaption></figure><p>Padding tokens are represented as <em>[0, 0, 0, 0, 0]</em>, so that they don’t trigger any quantity in the loss calculation.</p><h4>Metrics</h4><p>A real metric is needed to assess the model&#39;s performance. For this multi-class classification, a class-wise F1 score is relevant. This score is computed on each token: we considered one separate classification for each distinct token of the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g96oFVitIkfSdqRAbqTKhQ.png" /><figcaption>Classification example</figcaption></figure><p>The following confusion matrix stores the model&#39;s performance for the previous sample.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1FTW9eCyFoyBpeq4K3njVQ.png" /><figcaption>Confusion matrix for this sample.</figcaption></figure><p>Hence, we can simply cumulate each sample&#39;s prediction results into the same confusion matrix, and compute Precision, Recall and F1 scores.</p><p>What&#39;s more, this method also allows to compute a score for each label category, which is very precious for tuning the model parameters.</p><h4>Training</h4><p>We run the training with the following hyper parameters:</p><ul><li>Batch size : 16</li><li>Learning rate: 0.001</li><li>Optimizer: Adam</li><li>Number of iterations: 10,000</li></ul><h4>Results</h4><p>Hereafter are the first training curves we obtained. The model quickly overfits (from epoch 10). Although the model isn&#39;t learning much, the strong convergence of the training curve ensures a correct implementation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ui06Kmeyv2d6Td2dphvZzQ.png" /><figcaption>Overfitting model. Blue: Training. Red: Validation</figcaption></figure><p>These first runs reached a validation F1 score of approximately 78%.</p><p>To tackle the overfitting issue, various implementation choices have been made :</p><ul><li><strong>Using a pre-trained embedding</strong>. At first, the embedding was randomly initialized (sampled from uniform distributions). Unfortunately, the time needed to learn a correct representation is too long, and the model overfits even before having learnt correct word vectors. What&#39;s more, unknown words of the validation set have poor representations. We then decided to use <em>GloVe</em> word representations (dimension 50) to already have correct representation of most words of our corpus.</li><li><strong>Dropout</strong>. We added dropout operations in the Dense layers. Dropout is also added on recurrent connections of the LSTM, with a much smaller rate.</li><li><strong>Reduce weights amount</strong>. Overfitting occurs mainly because the model is too complex. We tried to reduce the model&#39;s complexity by reducing LSTM dimensions and vocabulary size.</li></ul><p>After updating these elements, the final convergence curves we obtained are much better. The model generalizes well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QnyCChbg8ejMf4grHY81ZQ.png" /><figcaption>Model training with good generalization. Training: Orange. Validation: Grey.</figcaption></figure><p>Final model&#39;s performances on the test set are displayed below. The final model reaches <strong>a validation F1 score of 82,3%</strong>, bringing a strong improvement over the first trainings.</p><p>We can compute an average F1 score weighted by the classes&#39; support. Excluding the &quot;O&quot; category that would unbalance the result, <strong>our model achieves a very good test F1 score of 76,4 %.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5LZ0sZLYkurmHBH5GjzuAQ.png" /><figcaption>Final test set performances.</figcaption></figure><h3>Some examples</h3><p>Let&#39;s get a glance on a couple of extractions. We developed, along with the AI models, a user interface to access the model&#39;s predictions on a text sample.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EtdT-VLQROE9q0ybzERTBg.png" /><figcaption>Entity Extraction user interface. Blue: Activity, Yellow: Group, Red: Location</figcaption></figure><p>The model manages to extract many entities of different type and complexities. In particular, performances on <em>activities </em>are very satisfactory, as they contain simple and common words: indeed, <em>production</em> wouldn&#39;t be tagged as an <em>Activity, </em>while <em>electricity production</em> is definitely an Activity sector.</p><h3>Next steps</h3><p>Next steps would consist in improving the model to current state of the art methods, implementing for instance:</p><ul><li>Further model fine-tuning (embedding &amp; layer dimensions)</li><li>Attention mechanisms</li><li>OpenAI Transformers</li><li>Contextual Language Models (ULMFit, ELMO, BERT, etc.)</li><li>Conditional Random Fields</li></ul><h3>References</h3><ul><li>Paper : <a href="https://www.aclweb.org/anthology/Q16-1026">Chiu &amp; Nicols, <em>Named Entity Recognition with Bidirectional LSTM-CNNs</em>, 2016.</a></li><li><a href="https://arxiv.org/pdf/1708.05604.pdf">Bucketing technique for sequence to sequence learning</a></li></ul><p>Similar research works are underway at ILLUIN Technology. Some of them are already shared on <a href="https://medium.com/www.medium.com/illuin">our blog page</a>.</p><p><em>Our team is constantly growing. Interested? We&#39;re hiring! <br></em><a href="https://www.illuin.tech/"><em>https://www.illuin.tech</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=632ba83d3d41" width="1" height="1" alt=""><hr><p><a href="https://medium.com/illuin/named-entity-recognition-with-bilstm-cnns-632ba83d3d41">Named Entity Recognition with BiLSTM-CNNs</a> was originally published in <a href="https://medium.com/illuin">Illuin</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nested Bi-LSTM for Supervised Document Parsing]]></title>
            <link>https://medium.com/illuin/https-medium-com-illuin-nested-bi-lstm-for-supervised-document-parsing-1e01d0330920?source=rss----7e66f049dad0---4</link>
            <guid isPermaLink="false">https://medium.com/p/1e01d0330920</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Wacim Belblidia]]></dc:creator>
            <pubDate>Mon, 19 Aug 2019 09:35:15 GMT</pubDate>
            <atom:updated>2019-08-20T18:16:32.643Z</atom:updated>
            <content:encoded><![CDATA[<h4>Structuring unstructured documents</h4><h4>A Deep Learning based supervised approach for text segmentation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8s-VzNIcca2gZ3JNLseODw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Z9VgMkehuH_bOZthwjH5g.jpeg" /></figure><p>Parsing a document consists in splitting its text into several <strong>blocks</strong> of semantic consistency. This classical NLP task is often referred as <em>text segmentation.</em></p><p>Parsing a document in order to extract structured information is a key challenge for many companies, that have either a <em>constant document stream </em>(insurances companies, health administrations), or <em>tremendous amounts of legacy document bases</em> (lawyers teams, consultancy firms, etc.).</p><p>This article walks through the implementation and training of a Deep Learning model that achieves document parsing on Wikipedia articles.</p><h3>Several approaches</h3><p>Various methods can be imagined to parse a text into blocks.</p><h4>Rule based</h4><p>Rules based methods consist in manually setting up strategies to look for keywords, seek some numbering along with titles, extract styles to identify section headers, or look for patterns in the document organisation. These simple rules can achieve satisfactory performances on documents that share a common formatting structure.</p><h4>Content-based</h4><p>As a human would do, the natural mindset for parsing a document is to read its content and detect when the content changes. Detecting semantic ruptures is very powerful, but requires to understand the text meaning.</p><p>Such understanding can be achieved with Machine Learning algorithms such as LDA (<em>Latent Dirichlet Allocation</em>) for topic modelling, TF-IDF (<em>Term Frequency, Inverse Document Frequency</em>) or Word Embeddings methods, that both build vectorized text representations.</p><p>A simple way to distinguish the blocks would then be to train a clustering algorithm such as K-Means or DBSCAN, and identify meaningful clusters of sentences.</p><h4>Supervised text segmentation</h4><p>In this approach, an algorithm is trained in a supervised mindset to detect separations in a document. The document is walked through sentence by sentence, and for each sentence the model predicts whether this piece of text starts a new block or not. <strong>This is the approach we selected.</strong></p><p>Very few annotated corpus are available in the open-source community. By using a semi-supervised learning paradigm, knowledge learnt on generic datasets can hopefully be transferred towards domain-specific corpuses, eventually with a very small of annotated documents.</p><h3>Our approach</h3><p>We implemented a supervised text segmentation approach proposed in March 2018 by a team of the <em>Tel-Aviv University </em>in <a href="https://arxiv.org/pdf/1803.09337.pdf">Koshorek et. al., <em>Text Segmentation as a Supervised Task.</em></a></p><h4>Data</h4><p>This approach uses the english Wikipedia corpus. Title headers of top-level sections are used to define the block boundaries. The first sentence of each section is labelled as a 1, and other sentences are labelled as 0. Of course, the headers’ text are removed, so that we only focus on the semantic ruptures from one paragraph to the next.</p><p>The learning target for each article is then a sequence of 0s and 1s. The research team released already processed Wikipedia corpuses containing the articles with highlighted block separations. The full dataset, <em>Wiki727k</em>, includes 727k Wikipedia articles. <em>For computation matters, we&#39;ll use only 10% of this huge dataset.</em></p><p>As a first approximation, too long documents are not processed, as they bring both convergence and memory challenges. We used the <em>95%</em> quantile value as an upper limit for article lengths, so that every article longer than 150 sentences is not processed.</p><p>The corpus is randomly split into a training (<em>80%</em>) and a validation (20%) sets. The complementary dataset <em>Wiki50</em>, containing only 50 articles, will be used as a test set.</p><h4>Preprocessing</h4><p>Classical preprocessing steps are applied :</p><ul><li>The text is <strong>lowercased </strong>for creating the embedding representations.</li><li><strong>Tokenization</strong>. Two tokenizations processes are applied : tokenizing articles into sentences, and sentences into words. We used <em>WordPunktTokenizer</em> and <em>SentencePunktTokenizer</em> from NLTK.</li><li>Digit characters are replaced by the special token “DIGIT”. For instance, the year “2019” will be replaced by “DIGIT DIGIT DIGIT DIGIT”. This way, we extract only the formatting information from these tokens, not the value.</li></ul><p>For instance, <a href="https://en.wikipedia.org/wiki/Johnston,_South_Carolina">this Wikipedia article</a> is represented as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7e7468b486062381e52714694cc9ed2/href">https://medium.com/media/e7e7468b486062381e52714694cc9ed2/href</a></iframe><h4><strong>Vocabulary management</strong></h4><p>As every Deep Leaning NLP applications, words are represented by their ids in a vocabulary, and then projected as <strong>continuous vectors </strong>in an embedding matrix. Correctly managing the size of our vocabulary is critical, as it directly impacts the number of trainable weights. Training the word embedding is a major part of the network’s convergence effort. A too large vocabulary might lead to poor convergence and most likely to overfitting.</p><p>Too keep a small enough vocabulary, we used the <em>Glove </em>embedding, that offers a pre-trained english word embedding space of dimension 50 (against 300 for Word2Vec or FastText embeddings).</p><p>In order to take into account the dataset specifics, we built a hybrid vocabulary between the <em>GloVe</em> pre-trained embedding and the corpus words. To do so, the vocabulary is built by combining the top 30k words of Glove with the top 5k from the dataset words (excluding the ones already in Glove).</p><p>The same approach has been adopted in another ILLUIN Technology research work, detailed below.</p><p><a href="https://medium.com/illuin/named-entity-recognition-with-bilstm-cnns-632ba83d3d41">Named Entity Recognition with BiLSTM-CNNs</a></p><h3>Model</h3><p>To solve this task, we trained a <em>Bi-LSTM</em> based neural network that learns a sentence embedding and predicts sentence-wise probabilities of starting a new block.</p><h4><strong>Architecture</strong></h4><p>Each sentence is projected into a <strong><em>sentence embedding</em></strong><em>, </em>and then processed by a LSTM layer. The <em>sentence embedding </em>is learnt from the word-level embeddings : a first recurrent network processes every word of the input sentence through two Bi-LSTM layers. The output sequence is <strong>max-pooled</strong> to get rid of the sentence length dependency. This way, <em>sentence embedding</em> vectors are of fixed size.</p><p>Then, the computed <em>sentence embedding</em> is passed as an input to a second recurrent neural network: Two Bi-LSTM layers process the input vectors. The final LSTM cell states are used to feed a final classification layer (<em>Sigmoid </em>activation) that predicts the binary label at each time step.</p><p>Embedding and LSTM dimensions are set up to 50.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zM2zJvgpcc4imKSwhGYsKw.png" /><figcaption>Nested Bi-LSTM for text segmentation</figcaption></figure><p>This architecture has been implemented in Keras. An overview of the network implementation is shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f8039a5c642fda3340940e3738a3a6c/href">https://medium.com/media/0f8039a5c642fda3340940e3738a3a6c/href</a></iframe><h3>Training</h3><p>We run the training with the following hyper parameters:</p><ul><li>Batch size : 16</li><li>Learning rate : 0.002</li><li>Optimizer : Adam</li><li>Number of iterations : 56,000</li></ul><p>The network is trained by minimizing an element-wise <em>binary cross-entropy </em>objective function :</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*j7suepiI6EpHuv3r.png" /><figcaption>Loss function : averaged binary cross-entropy, starting from sentence nº2. Yi : ground truth, Pi: predicted probability</figcaption></figure><p>Each timestep contributes through its <em>negative log-likelihood</em>. The first sentence is always labeled as 1 because it starts the first block, so the first timestep is not taken into account in the loss function. The loss is averaged, to get rid of the sentence length dependency.</p><p>Batch generation also contains some specifics, as it requires a double padding process. Indeed, a batch contains <em>b </em>articles, each of them containing a variable number of sentences <em>n_sentences</em>. Each sentence contains a variable number of words <em>n_words</em>. Hence, a batch is represented by a tensor of shape <em>(b, max_n_sentences, max_n_words)</em>, where <em>max_n_sentences </em>is the highest number of sentences contained in one article (among the <em>b </em>articles), and <em>max_n_words </em>is the longest sentence (token-wise) among all the sentences of the <em>b</em> articles.</p><p>Padding tokens are used to fill the tensors blanks, and ignored by the loss function during back-propagation.</p><h3>Results</h3><h4>Network convergence</h4><p>The convergence curves can be observed below. The accuracy metric doesn&#39;t make any sense for this task, as most labels are 0. Instead, let&#39;s dive into the <em>loss / precision / recall / f1 </em>metrics for training and validation phases, to get a glance on the network performances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-YFvxfjdO3882u2LlOMJOQ.png" /></figure><p>Overfitting occurs after epochs 70–80. Our final model is selected with an early stopping process. The final model can be picked following two main options:</p><ul><li>Selecting the epoch at which the loss value is minimal</li><li>Selecting the epoch where the loss value is in a minimum interval of, let&#39;s say, min_loss +/- 10%, while maximizing the validation F1 score. <em>Indeed, the convergence curves show that for a large epoch range (epochs 30 to 70), the loss stays quite close to its minimal value while the f1 still raises.</em></li></ul><p>Moreover, in order to assess the model performance, the classification threshold has to be tuned, as its value strongly influences the metric values. In order to choose the right threshold, we will use the <em>Pk</em> value (defined below).</p><h4>Metrics assessment</h4><p>The <em>Pk </em>score is mentioned in the paper as the main metric for text segmentation tasks.</p><blockquote>Pk is the probability that when passing a sliding window of size k over sentences, the sentences at the boundaries of the window will be incorrectly classified as belonging to the same segment (or vice versa).</blockquote><blockquote>Following (Glavas et al. , 2016), we set k to half of the average segment size in the ground-truth segmentation.</blockquote><p>We will use it to compare our model’s performance with the reference implementation, and also to set the classification threshold.</p><p><strong>The lower the Pk value is, the better.</strong></p><p>To tune the classification threshold, we computed Pk on the validation set for various values of the threshold. Results are shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-idMjKC6FH2WT1amgdL5eg.png" /><figcaption>Pk score for different classification threshold.</figcaption></figure><p><strong>0.3 seems like an optimal threshold value for this binary classification task.</strong></p><p>The final performance is assessed on the <em>Wiki50</em> dataset, used as an evaluation set in the paper.</p><p><strong>Our trained implementation reached a very satisfactory <em>Pk </em>score of 24,10% on the <em>Wiki50</em> test set.</strong> This score is lower than the exposed state-of-the-art<em> (18,24%)</em>, but still shows a massive improvement over the random baseline <em>(52,65%) </em>and the<em> GraphSeg </em>model<em> (63,56%</em>) <em>(both mentioned in the paper).</em></p><p>Several factors explain this performance difference :</p><ul><li>We trained only on a small part of the dataset (~10%)</li><li>Using a Glove embedding instead of Word2Vec <em>(because it&#39;s available in a smaller dimension)</em></li><li>Our embedding method differs : we tried using a custom method for merging the pre-trained and the custom dataset vocabulary in order to properly manage OOV words.</li><li>Small implementation details that might differ (Batch Normalization, Dropout, etc.)</li></ul><p>More research works are underway to implement a full pre-trained embedding method with a bigger training infrastructure.</p><p>Moreover, our trained model performs a F1 score of 61,15% on the <em>Wiki50</em> dataset.</p><h3>Segmentation examples</h3><p>Let’s get a concrete touch on the model’s performance. The following examples show the origin article, the parsed version of the text, and a macro segmentation view, for a couple of random articles from the <em>Wiki50</em> dataset. We picked a wide range of article sizes and themes.</p><p>On the macro visualisations, the ground truth article separators are shown in orange<em>, </em>and the predicted separators in blue<em>. The chosen threshold (0.3) is also displayed.</em></p><h4>Example 1 : Beer Checkers game article</h4><p><a href="https://en.wikipedia.org/wiki/Beer_checkers"><em>https://en.wikipedia.org/wiki/Beer_checkers</em></a></p><p><strong>Parsed text</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad740daa183b6129b502a4d400298bb3/href">https://medium.com/media/ad740daa183b6129b502a4d400298bb3/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c4ouGBUN3J0koabZVdY-xg.png" /><figcaption>Parsing visualization. The ground truth separators are perfectly predicted with pretty good confidences.</figcaption></figure><h4>Example 2: Jason Joseph Euell article</h4><p><a href="https://en.wikipedia.org/wiki/Jason_Euell">https://en.wikipedia.org/wiki/Jason_Euell</a><br><em>[Note: The current version of the article is slightly different. It might have changed after the Wiki50 dataset creation]</em></p><p><strong>Parsed version</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5316b3c4e0c17d682f39537308e0eec/href">https://medium.com/media/e5316b3c4e0c17d682f39537308e0eec/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Erzupg8M9xLdHXYxxtxeg.png" /><figcaption>Parsing visualization (much longer sentence). The ground truth separators are mostly all predicted (7/10), as the model lacks confidence. 2 false positives are also predicted.</figcaption></figure><h4>Example 3 : Microsoft BASIC</h4><p><a href="https://en.wikipedia.org/wiki/Microsoft_BASIC"><em>https://en.wikipedia.org/wiki/Microsoft_BASIC</em></a></p><p><strong>Parsed text</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/521c6284e9a84cd8d00564f339c653d0/href">https://medium.com/media/521c6284e9a84cd8d00564f339c653d0/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TyU0vMK2Ds5ZtaKwrgDNqg.png" /><figcaption>Parsing visualization.</figcaption></figure><h4>Wrap up &amp; Next steps</h4><p>We walked through the main steps of our research work about <strong>supervised text segmentation </strong>inspired from a 2018 paper from the <em>Tel-Aviv University</em>. Our implementation slightly differs from the paper&#39;s by its dataset size and its embedding process. We still achieved a good performance of <strong>24,10% <em>Pk </em>score, </strong>heading close to the 18,24% SOTA.</p><p>More research are underway to train our models with a full dataset and similar implementation choices.</p><p>Next steps are to go further in the text segmentation capability by implementing more advanced networks, including for instance attention mechanisms or pointer generator modules, such as the <a href="https://ntunlpsg.github.io/project/segbot/">SegBot model from NTU</a>.</p><h3>References</h3><ul><li><em>NLP State of the art tasks :</em> <a href="https://paperswithcode.com/area/natural-language-processing">https://paperswithcode.com/area/natural-language-processing</a></li><li><em>Paper</em> : <a href="https://arxiv.org/pdf/1803.09337.pdf">https://arxiv.org/pdf/1803.09337.pdf</a></li><li><em>Datasets (Wiki727k &amp; WikiTest50) : </em><a href="https://www.dropbox.com/sh/k3jh0fjbyr0gw0a/AADzAd9SDTrBnvs1qLCJY5cza?dl=0">https://www.dropbox.com/sh/k3jh0fjbyr0gw0a/AADzAd9SDTrBnvs1qLCJY5cza?dl=0</a></li><li>Goran Glavas et. al, <em>Unsupervised text segmentation using semantic relatedness graphs. Association for Computational Linguistics. </em><a href="https://www.aclweb.org/anthology/S16-2016">https://www.aclweb.org/anthology/S16-2016</a></li><li><em>Text segmentation Neural Net with pointer network: </em><a href="https://ntunlpsg.github.io/project/segbot/">https://ntunlpsg.github.io/project/segbot/</a></li><li>NTU Segbot article : <a href="https://ntunlpsg.github.io/project/segbot/">https://ntunlpsg.github.io/project/segbot/</a></li></ul><p>Similar research works are underway at ILLUIN Technology. Some of them are already shared on <a href="https://medium.com/www.medium.com/illuin">our blog page</a>.</p><p><em>Our team is constantly growing. Interested? We’re hiring! <br></em><a href="https://www.illuin.tech/"><em>https://www.illuin.tech</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e01d0330920" width="1" height="1" alt=""><hr><p><a href="https://medium.com/illuin/https-medium-com-illuin-nested-bi-lstm-for-supervised-document-parsing-1e01d0330920">Nested Bi-LSTM for Supervised Document Parsing</a> was originally published in <a href="https://medium.com/illuin">Illuin</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cleaning Up Dirty Scanned Documents with Deep Learning]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/illuin/cleaning-up-dirty-scanned-documents-with-deep-learning-2e8e6de6cfa6?source=rss----7e66f049dad0---4"><img src="https://cdn-images-1.medium.com/max/1134/1*j5bHXHipJGivFIWu42e1gA.jpeg" width="1134"></a></p><p class="medium-feed-snippet">CNN &amp; CycleGAN approaches for denoising image documents</p><p class="medium-feed-link"><a href="https://medium.com/illuin/cleaning-up-dirty-scanned-documents-with-deep-learning-2e8e6de6cfa6?source=rss----7e66f049dad0---4">Continue reading on Illuin »</a></p></div>]]></description>
            <link>https://medium.com/illuin/cleaning-up-dirty-scanned-documents-with-deep-learning-2e8e6de6cfa6?source=rss----7e66f049dad0---4</link>
            <guid isPermaLink="false">https://medium.com/p/2e8e6de6cfa6</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Kayo Yin]]></dc:creator>
            <pubDate>Tue, 30 Jul 2019 09:11:26 GMT</pubDate>
            <atom:updated>2019-07-30T09:41:24.895Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Convolutional Neural Networks for Medical Image classification]]></title>
            <link>https://medium.com/illuin/convolutional-neural-networks-for-medical-image-classification-c39b3b6b4c9a?source=rss----7e66f049dad0---4</link>
            <guid isPermaLink="false">https://medium.com/p/c39b3b6b4c9a</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[medical-image-analysis]]></category>
            <dc:creator><![CDATA[Wacim Belblidia]]></dc:creator>
            <pubDate>Thu, 16 May 2019 16:29:51 GMT</pubDate>
            <atom:updated>2019-05-16T16:35:25.718Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*sXVakYpSbgxyfpiy.jpg" /></figure><p>In October 2018, Illuin Technology had the chance to collaborate with the french Gustave Roussy Institute by participating in an AI-oriented radiology challenge for the 2018 edition of JFR (<em>Journées Francophones de Radiologie</em>).</p><p>More specifically, the goal was to train AI models to predict, based on radiological images (MRI, Scanner, etc.), various pathologies such as meniscus fissures, breast cancer tumours, kidney dysfunctions, thyroid cartilage or liver lesions.</p><p>This article details the challenges we faced and the technical approaches we developed. Main topics covered in this article are :</p><ul><li>Goals &amp; General setup of the prediction tasks</li><li>Data overview</li><li>Images preprocessing</li><li>Neural Networks training</li><li>Results</li></ul><h3>Goals &amp; Setup</h3><p>We focused on analysing MRI images of meniscus. These meniscus potentially contain a fissure, that we have to characterize. More precisely, the goal was to work on three binary classification tasks:</p><ul><li>Detecting the <strong>presence of a meniscal fissure</strong> on the image : <em>present </em>or<em> absent</em>.</li><li>Understanding its <strong>orientation</strong> : is the fissure <em>horizontal</em> or <em>vertical ?</em></li><li>Understanding its <strong>position</strong> : is the fissure located in the <em>anterior</em> or <em>posterior</em> part of the knee structure ?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*ZSL7YHlLP5qbsOswjJpkBA.png" /><figcaption>Overview of an horizontal, anterior meniscus fissure</figcaption></figure><p>For instance, on the knee MRI above, there is a <strong>horizontal-oriented</strong> meniscal fissure, located on the <strong>anterior</strong> knee area.</p><p>To tackle this project, we&#39;ve been leading various explorations to build the best model. We mainly compared two approaches :</p><ul><li><em>Option 1</em> : Segmenting the two meniscus zones (small triangles) where the meniscal tear are to be found, and analysing the extracted zones</li><li><em>Option 2</em> : Processing the image entirely, without any segmentation</li></ul><p>The second option was selected, as its was a more straightforward approach. Also, we assumed that keeping the whole bone structure would help in determining the position (anterior or posterior) of the fissure. We first applied <strong>preprocessing operations </strong>on the images, before training <strong>convolutional neural networks</strong> for each label.</p><h3>Data Overview</h3><p>The data consists of 1128 meniscus images. Out of these 1128 knee images, 25 % contain a fissure. In these 282 fissure images, 9% are located on the <em>anterior</em> part of the knee, and 91% on the <em>posterior</em> part, while <em>horizontal</em>/<em>vertical</em> repartition of these fissures is more balanced (60%/40%).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*OaeTOJ0k3_h6j0BKOlVQVA.png" /><figcaption>One image sample, with a horizontal fissure</figcaption></figure><p>A few images contain a double meniscal fissure (on the anterior and posterior part of the knee structure). A few other images do not have the right size (256, 256). These images are put apart for the training task to be consistent.</p><p>Training, validation and test sets were created with 70, 20, and 10% of the images respectively.</p><h3>Images Preprocessing</h3><p>In order to highlight efficient features for medical diagnosis, various computer vision operations are applied.</p><h4>Filtering</h4><p>First, filtering processes allow edge detection and contrast enhancement. Hereafter are shown various filtering operations, that aims at highlighting the anatomical structures of the given knee : Sobel, Laplace and Schaar filters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LhXgJZ0Y33fCNBQQ" /><figcaption>Various filtering processes on meniscus images</figcaption></figure><p><strong>Sobel</strong> filter achieved great results on edge detection. It allowed an efficient highlight of the main bones and the two knee meniscus. Benchmarking these 3 filtering processes, Sobel filter have had a positive impact on our classification performances. The filtered image is added to the original image as a 2nd channel, so that we still keep the original information.</p><h4>Normalization</h4><p>Moreover, as images can have very different pixel value distributions, sample-wise image standardization is run to balance various brightness and contrast levels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DLlo_Z8VxVnP9J-REYX7-w.png" /><figcaption>Sample-wise image standardization</figcaption></figure><h4>Data Augmentation</h4><p>Also, as the training dataset is quite small, a robust <strong>data augmentation strategy</strong> is required :</p><ul><li>Random image rotation, between -45° and +45°</li><li>Random horizontal translation, between -20% and +20% of the image width</li><li>Random vertical translation, between -20% and +20% of the image height</li></ul><p>We kept the augmentation amplitudes quite low, to avoid too much confusion for the networks, especially on the position and orientation predictions. Indeed, a vertical oriented fissure becomes horizontal with a 90° rotation, and anterior and posterior locations can be confused with a 180° rotation. Of course, the surrounding bone structures can help assessing the correct answer, but we preferred keeping it simple.</p><p>Various augmented versions are shown on the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*hQ-xbXj9xqP-jmANxlUlDg.png" /></figure><p>Let&#39;s now understand the way we trained these 3 classification tasks.</p><h3>Neural Networks training</h3><h4>Multi-task paradigm</h4><p>First, the training paradigm for achieving the 3 predictions is not straightforward. First option would consist in training a multi-label classification algorithm. But the 3 labels are interdependent: indeed, we don&#39;t want to predict the orientation and location of a meniscus fissure if the predicted label for its presence is <em>False</em>.</p><p>Hence, we chose to train 3 separate neural networks : the <strong>fissure detection</strong> network, the <strong>orientation classification </strong>network, and the <strong>position classification </strong>network.</p><p>The <em>fissure detection</em> network was trained with the whole dataset, while the <em>orientation </em>and<em> position</em> networks were fed only with training images that contained a meniscal fissure. At inference time, these networks are used only if the fissure detection network classifies a <em>Yes </em>for the fissure presence.</p><p>A more complex set up would be to train the 3 models with <em>a common image-representation block</em>. The feed-forward for each model would enrich a common representation, instead of training separately the three representations. This solution requires some time and effort on the implementation, in order to separately back-propagate the gradients on a shared image representation for the three models. This setup has not been implemented so far, and is an important part of our next research works.</p><h4>Network architectures</h4><p>As a reminder, we feed the networks with the original image, stacked with its Sobel-filtered version. The input image is hence of shape (2, 256, 256).</p><p>The 3 networks are pretty similar. They are based on simple convolutional and pooling layers for extracting meaningful features from the images. At the end, three fully-connected layers are used, including one final unit for binary classification. Dropout is used both on dense layers and convolutional blocks to keep a good enough generalisation capability. The precise setup for each network is shown on the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yz49tDnoItCLHa128SIzHg.png" /><figcaption>3 Convolutional Blocks (kw : 7, 5, 3), 3 Dense Layers (32, 16, 1)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ge3WM5nOfiyu2SMnNdXzIw.png" /><figcaption>4 Convolutional Blocks (kw : 7, 5, 3, 3), 3 Dense Layers (32, 16, 1) — Trained only on images with fissure=1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oLxcd7L-UAlMXD_L9K9Mdg.png" /><figcaption>4 Convolutional Blocks (kw : 7, 5, 3, 3), 3 Dense Layers (32, 16, 1) — Trained only on images with fissure=1</figcaption></figure><p>We experimented some transfer learning from the ResNet50 and VGG16/19 representations, but it didn&#39;t bring any better results. It appears that medical images are too specific, and hence too far from what pre-trained image representation models already know. We also experimented CNN based auto-encoders representations, that were rather inconclusive.</p><h4>Training</h4><p>The 3 models were trained with the common <em>binary cross-entropy </em>loss function. We benchmarked a large grid of hyper-parameters. The final set of parameters we chose was :</p><ul><li>Batch size : 32</li><li>Learning rate : 0.001</li><li>Optimizer : Adam</li><li>80 training steps per epoch, 20 validation steps.</li><li>Dense dropout rate : 0.4</li><li>Convolutional dropout rate : 0.2</li></ul><p>Moreover, learning rate is dynamically adapted to the training behaviour. It is regularly halved based on the AUC metric evolution (Area Under Curve, that stands for the AUROC metric). Overfitting still occurs after 2500 to 3000 iterations (~35 epochs). We hence applied an <strong>early stopping policy</strong> to stop the model right before the overfitting starts.</p><p>Training (in grey) and validation (in orange) curves are available on the plots below, including <em>accuracy</em>, <em>AUC</em> and <em>loss </em>evolutions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*sTS0ltFt25PyeWASjkP9NA.png" /><figcaption>Training metrics for meniscal tear detection</figcaption></figure><h3>Results</h3><h4>Inference process</h4><p>At inference time, images are also augmented, but with a smaller amplitude for the rotation operation, to minimize the impact on the original image. An ensembling (voting) strategy is also applied : the models are run on the original image + 5 randomly augmented versions of the original image. The predicted values are averaged for the final prediction.</p><h4>Final performances</h4><p>The JFR DataChallenge team assessed a performance score based on AUC values for each prediction task. More precisely, a weighted average score is computed based on the 3 AUC scores, with 40% for the <em>fissure detection</em> task and 30% for the two other tasks.</p><p>On our own test sets, we achieved task-wise AUC scores of :</p><ul><li>92,22 % for the <em>fissure detection </em>network</li><li>92,30 % for the <em>orientation </em>network</li><li>82,14 % for the <em>position</em> network</li></ul><p>These scores correspond to a global score of 89,72 %.</p><p>An evaluation set was released at the very end of the challenge to compute final team scores. On this final set, we achieved a 84,6 % performance, reaching the 3rd best score (out of 11 teams).</p><h3><strong>Conclusion &amp; Next steps</strong></h3><p>More research works are underway. Main next steps consists in :</p><ul><li>Training a common image representation with shared training processes</li><li>Deep diving on image segmentation neural networks to extract meniscus areas before classification</li><li>Exploring the meniscus areas segmentation also with classical computer vision algorithms (edge detection, dilation, erosion, thresholding, etc…)</li><li>Enriching the filtering pipeline</li><li>Working on deeper augmentation generators with blurring, noising or contrast operations</li></ul><p>As a wrap up, we achieved good classification performances on these radiological diagnosis. Strong filtering strategies and Deep Learning models are both involved in these promising results.</p><p>Future research works for AI-based healthcare diagnosis tools are planned for the incoming AI Challenge for Health (#AIParisRegion, <a href="https://www.aichallenge.parisregion.eu/health-challenge/">https://www.aichallenge.parisregion.eu/health-challenge</a>).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c39b3b6b4c9a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/illuin/convolutional-neural-networks-for-medical-image-classification-c39b3b6b4c9a">Convolutional Neural Networks for Medical Image classification</a> was originally published in <a href="https://medium.com/illuin">Illuin</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>