<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sebastian on Medium]]></title>
        <description><![CDATA[Stories by Sebastian on Medium]]></description>
        <link>https://medium.com/@duerr.sebastian?source=rss-42e263a889aa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*uPl5gR2cg3yVGfqH</url>
            <title>Stories by Sebastian on Medium</title>
            <link>https://medium.com/@duerr.sebastian?source=rss-42e263a889aa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 03:51:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@duerr.sebastian/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Making Neural Search Queries Accessible to Everyone with Gradio & Haystack]]></title>
            <link>https://medium.com/@duerr.sebastian/making-neural-search-queries-accessible-to-everyone-with-gradio-haystack-726e77aca047?source=rss-42e263a889aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/726e77aca047</guid>
            <category><![CDATA[semantic-search]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[gradio]]></category>
            <category><![CDATA[haystack]]></category>
            <dc:creator><![CDATA[Sebastian]]></dc:creator>
            <pubDate>Tue, 26 Apr 2022 19:41:38 GMT</pubDate>
            <atom:updated>2022-05-11T20:17:56.662Z</atom:updated>
            <content:encoded><![CDATA[<h3>Making Neural Search Queries Accessible to Everyone with Gradio — Deploying Haystack’s Semantic Document Search with Hugging Face models in Gradio in Three Easy Steps</h3><h4>In this article, we are going to help non-technical users benefit from semantic document search in pdf documents by providing them a straightforward interface via Gradio by Hugging Face.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fWN8RdPouEJiXrES" /></figure><h3>Introduction</h3><p>Phil is an enterprise account executive from a digital corporation. He faces the problem of efficiently extracting information from corporate annual business reports. In a previous <a href="https://medium.com/p/8e0cac743c7d">article</a>, we were looking at the <a href="https://corporate.walmart.com/media-library/document/2020-walmart-annual-report/_proxyDocument?id=00000171-a3ea-dfc0-af71-b3fea8490000">10-k business plan</a> of Walmart Inc. Semantic document search can help Phil tremendously.</p><blockquote><strong>Update: </strong>Now, you can try the service on <a href="https://huggingface.co/spaces/seduerr/semantic_search">Hugging Face Spaces</a>.</blockquote><h3>Table of Contents</h3><ul><li>A Look at the End Result</li><li>Making Semantic Search accessible with Gradio App in 3 Steps</li><li>Extensions of the Gradio App</li><li>Next Steps regarding Gradio &amp; Haystack</li><li>Summary</li></ul><p>Semantic search is powered by deep neural nets and allows you to search documents based on similar phrasing and context (<a href="https://www.deepset.ai/blog/what-is-text-vectorization-in-nlp">word embeddings</a>). This article by deepset.ai explains the specificities of <a href="https://www.deepset.ai/blog/understanding-semantic-search">semantic document search</a>. In their article, the authors provide an intuitive illustration towards Semantic Document Search which is finding similar documents to queries:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*m9-O0CHAY7-1WLjF" /><figcaption>Semantic document search: Find the most similar document (e.g. paragraphs or sentences) to a query</figcaption></figure><p>With deepsets.ai’s Haystack framework, we can answer Phil’s questions about a corporation’s situation in a given business report. He uses this knowledge to prepare for important sales calls in an efficient manner.</p><h3>A Look at the End Result: Our Final User Interface with Gradio App</h3><p>In this previous <a href="https://medium.com/p/8e0cac743c7d">article</a>, we introduced how to run semantic document search within pdf documents from Jupyter notebooks. <strong><em>However</em>, </strong>there is one caveat: Since Phil is not a NLP engineer, we want to make sure that our semantic document search can be used in a convenient way. Therefore, we are going to create a front end to allow Phil to rapidly and securely make use of the tool on his machine. All code of this project is available in this <a href="https://github.com/seduerr91/pdf-eqa">Github repository</a>.</p><p>How will we achieve this? We will build a Gradio app with semantic document search capabilities. Let us take a look at what our Gradio app will look like once we are done:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9zjA3hNax1H8mSjh" /></figure><p>After having imported our dependencies, we have to follow three simple steps in order to search pdf documents intelligently. In addition to the Haystack dependencies, we need Gradio. The requirements to install these modules with pip can be found in the accompanying <a href="https://github.com/seduerr91/pdf-eqa">git repository</a> in the <em>requirements.txt</em>.</p><pre>from haystack.nodes import FARMReader, PreProcessor, PDFToTextConverter, DensePassageRetriever<br>from haystack.nodes import ElasticsearchRetriever<br>from haystack.document_stores import ElasticsearchDocumentStore<br>from haystack.pipelines import ExtractiveQAPipeline<br>from haystack.utils import launch_es<br>import gradio as gr</pre><h3>Making Semantic Search accessible with Gradio App</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4opadU48Den8Tt_j" /></figure><p>In step 1, we introduce a few functions to be able to use Haystack within Gradio and to optimize our semantic document search for speed.</p><p>First, we define our preprocessor. If you are unsure about how to set these parameters, this comprehensive article on <a href="https://www.deepset.ai/blog/parameter-tweaking-get-faster-answers-from-your-haystack-pipeline">parameter tweaking</a> provides guidance.</p><pre><strong>preprocessor</strong> = PreProcessor(<br> clean_empty_lines=True,<br> clean_whitespace=True,<br> clean_header_footer=True,<br> split_by=”word”,<br> split_length=100,<br> split_respect_sentence_boundary=True,<br> split_overlap=3<br>)</pre><p>As we have seen in the gif above, we are able to glance at the results of our questions. However, how can we get an indication that these results are meaningful? Well, we use the confidence of the neural net as a bearing. For this, we provide the “score” of any search result. [Additionally, we could also show the context in which the answer was identified by appending the “context” to the list of fields.]</p><pre><strong>def print_answers(results):</strong><br> fields = [“answer”, “score”] # “context”<br> answers = results[“answers”]<br> filtered_answers = []<br> for ans in answers:<br>      filtered_ans = {<br>        field: getattr(ans, field)<br>         for field in fields<br>           if getattr(ans, field) is not None<br>      }<br> filtered_answers.append(filtered_ans)<br> return filtered_answers</pre><p>Also, we need a ‘run_once’ function to ensure that we are reading and analyzing a pdf document when it is uploaded only once (we will use this function as a <a href="https://towardsdatascience.com/how-to-use-decorators-in-python-by-example-b398328163b">decorator</a> later). This way, we do not have to prepare a pdf every single time we ask a question, but we can retrieve multiple questions from it.</p><pre><strong>def run_once(f):<br>    def wrapper(*args, **kwargs):</strong><br>       if not wrapper.has_run:<br>       wrapper.has_run = True<br>           return f(*args, **kwargs)<br>       wrapper.has_run = False<br>           return wrapper</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9JDd3i-c1BfMl2m4zeKtIw.png" /></figure><p>There is little left to make semantic document search work: We initialize our reader, load the document store, and initialize our retriever. To get results fast, we will use a sparse retriever here. The notable differences <a href="https://www.deepset.ai/blog/save-resources-with-query-classifier-for-neural-search">between sparse and dense retrieval methods</a> are speed and quality.</p><pre><strong>launch_es()<br>reader</strong> = FARMReader(model_name_or_path=”deepset/roberta-base-squad2&quot;)<br><strong>document_store</strong> = ElasticsearchDocumentStore(host=”localhost”, username=””, password=””, index=”document”)<br><strong>retriever_es</strong> = ElasticsearchRetriever(document_store=document_store)<br><strong>pipe</strong> = ExtractiveQAPipeline(reader, retriever_es)</pre><p>As a last step before querying, we need to process the pdf document. We convert the pdf into text chunks, preprocess them (with the parameters that we defined in the beginning of step 2), and write them into the ElasticSearch Document store.</p><pre>@run_once # use a decorator, as we process the pdf only once.<br><strong>def written_document(pdf_file):</strong><br> <strong>converter</strong> = PDFToTextConverter(remove_numeric_tables=True, valid_languages=[“en”])<br> <strong>document</strong> = [converter.convert(file_path=pdf_file.name, meta=None)[0]]<br> <strong>preprocessed_docs</strong> = preprocessor.process(document)<br> <strong>document_store</strong>.write_documents(preprocessed_docs)<br> return None</pre><p>Now, we use the document chunks from the document store, and run queries (i.e., we ask questions) on them. If the current results are too slow, then we can get <a href="https://www.deepset.ai/blog/parameter-tweaking-get-faster-answers-from-your-haystack-pipeline">faster answers</a> by adjusting the <em>top_k</em> value of the retriever. A retriever is an excavator. It sifts through a large amount of documents by performing quick vector computations to find the best candidate documents for the reader. Think of the reader as a pickaxe. It looks only at the candidates and passes them through a pre-trained transformer model that determines which answer fits a query best.</p><pre><strong>def predict(question, pdf_file):</strong><br> written_document(pdf_file)<br> result = pipe.run(query=question, params={“Retriever”: {“top_k”: 20}, “Reader”: {“top_k”: 5}})<br> answers = print_answers(result)<br> return answers</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C8aEiS4gXd9YREF3" /></figure><p>Congratulations! We just set up a semantic document search tool. Now, let us make it accessible to Phil! <a href="http://www.gradio.app/">Gradio.app</a> is amazing. The team behind it created a very straightforward approach to making machine learning models testable. Let us explore some of its very cool features that will be helpful for Phil.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Rta41pfWvZB8cZlv" /></figure><p>Launching this front-end is as easy as (1) plugging in a predict() function, (2) defining inputs (we use both a text box for the question query, and a file uploader for the pdf document to search through), and (3) define the output which will be text. That’s it.</p><h3>Extensions of Gradio App</h3><p>Yet, there are some nice additional features, such as a flagging option (to vote on the quality of the result), an interpretation tool (that allows us to understand how the answers were formed), and a theme chooser (we are using the dark-grass one in this very instance). In the code below, we can read how you can make these amendments.</p><pre>title = “Search PDF Business Reports with Sparse Passage Retrieval”<br>iface = gr.Interface(fn=predict,<br> inputs=[gr.inputs.Textbox(lines = 3, label=’Ask an open question!’),<br> gr.inputs.File(file_count=”single”, type=”file”, label=”Upload a pdf”)<br> ],<br> outputs=”text”,<br> title=title, <br> flagging_options=[“top”, “medium”, “bad”],<br> interpretation=”default”,<br> theme=”dark-grass” # “default”, “huggingface”, “dark-grass”, “peach”<br> )</pre><p>Yet, Gradio does not stop there. You can run your Gradio app locally out of jupyter, in your local browser, or through a web api if you activate the ‘share=True’ comment. Oftentimes, it makes sense to prevent your tool from unintended use. For these situations, you can protect your Gradio app with a user and password combination. This is as simple as adding ‘auth’ with a login name and a password to the <em>Interface</em>. We even can enable a queue if we have a lot of server requests.</p><pre>iface.launch(<br> # share=True,<br> # auth=(“admin”, “pass1234”),<br> # enable_queue=True<br>)</pre><p>If we run this last instruction, then we get the following interface:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6T_1-KleGr6WpvAL" /></figure><p>This was easy! We just learned how to use semantic document search with one of the best open-source semantic document search solutions and explored Gradio as a means to make our tool instantly usable. Last, let us look at a few further steps, and summarize our findings.</p><p>Now, we can ask Phil’s questions through a front end! When using the tool, mind that extractiveQA does well in searching for answers in large text corpora. Hence, questions should be phrase with question words (“What are efforts regarding digital experiences?”) rather than as yes/no questions (“Are efforts for digital experiences?”). If the question would be phrased so that the answer shall be yes or no, then a deep neural net has a hard time finding the correct answer in the documents (credits &amp; thanks to Tuana from deepset.ai!).</p><h3>Potential Next Steps:</h3><h4>@Gradio App</h4><ul><li>We can build an actual web-app that gives us even a bit more convenience.</li></ul><h4>@Haystack Semantic Search</h4><ul><li>Use a reader model that is trained or, at least, fine-tuned on 10-k, 10-q, financial reports. An example on how to do that can be found in <a href="https://colab.research.google.com/github/deepset-ai/haystack/blob/master/tutorials/Tutorial2_Finetune_a_model_on_your_data.ipynb">tutorial 2 by deepset.ai</a>.</li><li>Using different retrieval algorithms (sparse vs. dense) which is done in <a href="https://colab.research.google.com/github/deepset-ai/haystack/blob/master/tutorials/Tutorial1_Basic_QA_Pipeline.ipynb">tutorial 1 (sparse) by deepset.ai</a> and <a href="https://colab.research.google.com/github/deepset-ai/haystack/blob/master/tutorials/Tutorial6_Better_Retrieval_via_DPR.ipynb">tutorial 6 (dense) by deepset.ai</a>.</li><li>Also, next generation semantic document search techniques as in <a href="https://www.deepset.ai/blog/understanding-semantic-search">understanding semantic search</a> can help us.</li></ul><h3>Summary</h3><p>Based on the business need of senior sales account executive Phil, we used the Haystack framework from <a href="http://deepset.ai/">deepset.ai</a> for querying annual financial reports from S&amp;P 500 company Walmart. Additionally, we rapidly iterated a front-end by using Hugging Face’s Gradio.</p><p>While this solution is incredibly fast for developing MVPs/sharing your models, we still have a few aspects to optimize. Also, it is important that users understand that the way they ask questions is crucial.</p><h3>Thank you deepset.ai &amp; Hugging Face</h3><p>Deepset.ai’s Haystack and Hugging Face’s Gradio are so cool! With these two frameworks, one can essentially get an immediate solution to tedious processing of pdf documents to get reasonable context-based results. Thanks to <a href="http://www.deepset.ai/">deepset.ai</a>, <a href="http://huggingface.co/">Hugging Face</a> and <a href="http://gradio.app/">Gradio</a> for offering such amazing integrations and possibilities.</p><p>Thank you for reading this article and for any comments, Seb.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=726e77aca047" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gain valuable corporate insights from a 10-k report in 5 easy steps with dense passage retrieval]]></title>
            <link>https://medium.com/@duerr.sebastian/gain-valuable-corporate-insights-from-a-10-k-report-in-5-easy-steps-with-dense-passage-retrieval-8e0cac743c7d?source=rss-42e263a889aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e0cac743c7d</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[deepset]]></category>
            <category><![CDATA[deeplearing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Sebastian]]></dc:creator>
            <pubDate>Sun, 17 Apr 2022 09:01:22 GMT</pubDate>
            <atom:updated>2022-04-26T20:13:07.727Z</atom:updated>
            <content:encoded><![CDATA[<h3>Gain valuable corporate insights from a 10-k report in 5 easy steps with dense passage retrieval (DPR) and extractive question answering (extractiveQA) using deepset.ai’s Haystack</h3><h4>In this article, we are going to help sales account executive Phil extract useful knowledge from corporate annual report pdfs with the help of deep learning (we use dense passage retrieval (DPR) and extractive question answering (eQA)).</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/0*kdA8WPpZeL0KTstL" /></figure><h4>Table of Contents</h4><ul><li><strong>The Setup</strong>: A Sales Account Executive’s Approach to Cold Calling</li><li><strong>Beginning with the End in Mind</strong>: Taking a peek at the final result</li><li><strong>Implementing a tool to auto-extract knowledge</strong> from 10-k annual reports in 5 steps</li><li><strong>The results</strong>: investigation and interpretation</li><li><strong>Next steps</strong>: Improvements and Accessibility</li><li><strong>Summary</strong></li></ul><h3>The Setup: A Sales Account Executive’s Approach to Cold Calling</h3><p>Phil works for a large digital corporation as an executive account manager. With thirty big accounts a year, he is very, very careful on who to engage with. And before he speaks with his accounts, he makes sure he knows everything about their space. Therefore, he reads corporate annual reports (<a href="https://www.investopedia.com/terms/1/10-k.asp">10-k</a>), and looks for certain aspects such as:</p><blockquote>Does the target company make digital experiences a strategic initiative?</blockquote><p>If they do, then he has a reason to contact someone at that company. Since Phil is calling his contacts live, it’s absolutely vital he is well informed about their business’s strategic initiatives before he ever picks up the phone.</p><p>Phil told me that he would benefit most from a tool that could accurately and quickly identify strategic insights from business reports simply by asking the tool a set of key questions.</p><h4>Phil’s Questions:</h4><p>An ExtractiveQA model will only be able to find answers to a question, if the answer exists in the documents it’s looking at. And this is why a Yes/No question isn’t idea. Hence we’ve rephrased the first question ‘<em>Does the target company make digital experiences a strategic initiative?’, </em>and additional questions of Phil as:</p><ul><li>What efforts are being made in regards to digital experiences?</li><li>What are the strategic priorities?</li><li>What is the company’s growth?</li></ul><p>Let’s find answers to these questions!</p><h4>The business benefit of DPR and eQA</h4><p>For the purpose of this tutorial, I downloaded five arbitrary pdf 10-k business reports (Apple, Broadcom, Pfizer, Salesforce, Walmart), to test our setup. These sample reports and all the accompanying code can be viewed in my <a href="https://github.com/seduerr91/dpr_eqa.git">Github repo</a> (incl. requirements.txt for dependencies).</p><p>Our five business reports combine 483 pages with approximately 450 words per page. This results in around 220,000 words. Assuming that the ordinary person reads 300 words per minute, the time it takes to read these reports cumulates to 12 hours.</p><p>Yet, an implementation as presented in this article can cut the time to identify and extract key findings for Phil dramatically.</p><h3>Beginning with the end in mind</h3><p>Before we start, let’s have a look at what we will achieve by the end of this article. We will ultimately build a tool to answer Phil’s questions. Here is an example of what the tool provides when we ask the exemplary question <em>“What are the strategic priorities?”</em> in <a href="https://corporate.walmart.com/media-library/document/2020-walmart-annual-report/_proxyDocument?id=00000171-a3ea-dfc0-af71-b3fea8490000">Walmart’s annual report</a>:</p><p>Phil may immediately spark a conversation with the CMO of Walmart and discuss how Phil’s digital experience product can enable Walmart to improve their ‘<em>customer-facing initiatives by helping to create a seamless omni-channel experience for their customers</em>.’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eVXW60MS2ewRdwBONaywfA.jpeg" /><figcaption>Answers to questions ‘What are strategic priorities?’ (actual answers marked in blue)</figcaption></figure><p>[In case you have any issues with installing Haystack, there are some instructions at the end of this article. You can also join the <a href="https://haystack.deepset.ai/community/join">Haystack slack</a>. Everyone is very helpful and friendly!]</p><h3>Implementing a tool to auto-extract knowledge from 10-k annual reports</h3><p>In the following, we take five steps to help Phil to get answers to his questions with deepset.ai’s Haystack framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IcOa2vslBw9nzbt7" /></figure><p><strong>In Step 1</strong>: We load a sample 10-k report pdf and transform it to text with optical character recognition (OCR).<br><strong>In Step 2</strong>: We preprocess the texts by cleaning them.<br><strong>In Step 3</strong>: We set up the retriever with our requirements for 10-k reports.<br><strong>In Step 4</strong>: We set up the reader with our requirements for 10-k reports.<br><strong>In Step 5</strong>: We use both the retriever and reader to analyze the 10-k report of Walmart.</p><p>Before we begin, we have to import our dependencies.</p><pre><strong>from</strong> haystack.utils <strong>import</strong> convert_files_to_docs, export_answers_to_csv<br><strong>from</strong> haystack.nodes <strong>import</strong> FARMReader, DensePassageRetriever, PreProcessor, PDFToTextConverter<br><strong>from</strong> haystack.document_stores <strong>import</strong> FAISSDocumentStore<br><strong>from</strong> haystack.pipelines <strong>import</strong> ExtractiveQAPipeline<br><strong>import</strong> pandas as pd</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vmICEOyEGSVufhYF" /></figure><p>First, we convert our pdf reports to text. The function ‘convert_files_to_docs’ reads multiple text files (txt or .docx files) and parses them to text. Honestly, this is so cool. We can also use OCR to read in strictly formatted business reports. Let us do this only with the Walmart report to reduce complexity in this article. It’s also not difficult as you can see below. Kudos to deepset.ai for integrating xpdf!</p><pre># we can import all reports in one go with:<br># all_docs = convert_files_to_docs(dir_path=&quot;reports/&quot;)</pre><pre># in this instance, we only use the report of Walmart, but feel free to use other ones with<br>converter = PDFToTextConverter(remove_numeric_tables=True, valid_languages=[&quot;en&quot;])<br>all_docs = [converter.convert(file_path=&quot;reports/walmart-10k.pdf&quot;, meta=None)[0]]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VOuU32IJoG04-OBE" /></figure><p>Next, we preprocess the text of the docs, with the ‘preprocessor’, by setting a few parameters that should improve the results further along the way. The parameters have the following purposes:</p><ul><li>clean_empty_lines: This removes empty lines if there are more than two of them.</li><li>clean_whitespace: This removes leading and trailing whitespaces in a document part.</li><li>clean_header_footer: Uses a heuristic to clean headers and footers.</li><li>split_by: Type we will split a document by. This can be a word, sentence or passage.</li><li>split_length: Only documents with less than the length of the split_by value (like only 150 words).</li><li>split_respect_sentence_boundary: Respect the boundaries of a sentence when splitting.</li></ul><p>In their article on <a href="https://www.deepset.ai/blog/parameter-tweaking-get-faster-answers-from-your-haystack-pipeline">parameter tweaking</a>, the authors of Haystack recommend to <strong>split_by ‘word’</strong> as sentence and passage may fluctuate widely in combination with a <strong>split_length of ‘100’</strong> words. Additionally, it is suggested to avoid loss of context when splitting sentences by setting <strong>split_respect_sentence_boundary to ‘True’</strong>. Finally, use the sliding window method (setting <strong>split_overlap</strong> to a positive integer, e.g. <strong>3</strong>) to maintain context for the encoding (mind: this will inflate the corpus).</p><pre># Setting our parameters for the preprocessing<br>preprocessor = PreProcessor(<br>    clean_empty_lines=True,<br>    clean_whitespace=True,<br>    clean_header_footer=True,<br>    split_by=&quot;word&quot;,<br>    split_length=100,<br>    split_respect_sentence_boundary=True,<br>    split_overlap=3<br>)</pre><pre># Actual preprocessing<br>preprocessed_docs = preprocessor.process(all_docs)</pre><p>Now, we instantiate the document store, and write all pre-processed documents to it.</p><pre><strong>try:</strong><br>    # Instantiate the document store<br>    document_store = FAISSDocumentStore(faiss_index_factory_str=”Flat”)<br>    # Save all preprocessed documents to the document store<br>    document_store.write_documents(preprocessed_docs)<br><strong>except</strong> ValueError:<br>    # Reset document store, to make sure it is fine :)<br>    document_store.delete_documents()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T-fk3A41tKkohQR7" /></figure><p>At this point, we have our pre-processed documents in the document store. Next, we need to prepare them (retrieve them for analysis with a deep neural net). Retrievers help narrowing down the scope for the reader by identifying relevant documents to pass on to a reader.</p><p>This ‘narrowing down’ can be done with:</p><ul><li><em>Sparse retrievers</em>: algorithms based on counting the occurrences of words (bag-of-words) <em>or</em></li><li><em>Dense retrievers</em>: use neural network models to create “dense” embedding vectors (embeddings are a type of word representation that allows words with similar meaning to have a similar representation).</li></ul><p>We could use a sparse retriever to optimize for speed, but since this is a small example we’ll use a dense retriever in the proceedings to optimize for quality.</p><pre># We set up our retriever with the preferred parameters.<br>retriever = DensePassageRetriever(<br>    document_store=document_store,<br>    query_embedding_model=&quot;facebook/dpr-question_encoder-single-nq-base&quot;,<br>    passage_embedding_model=&quot;facebook/dpr-ctx_encoder-single-nq-base&quot;,<br>    max_seq_len_query=64,<br>    max_seq_len_passage=256,<br>    batch_size=16,<br>    use_gpu=True,<br>    embed_title=True,<br>    use_fast_tokenizers=True,<br>)</pre><pre># We calculate the embeddings for all of our documents in the document store<br>document_store.update_embeddings(retriever)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t0AcUesSYWJI1Bqm" /></figure><p>Next, we need a Reader. A reader scans the texts given by retrievers in detail and extracts the best answers. Readers are based on deep learning models. A reader with its QA model is the most expensive component of a question-answering pipeline — both computationally and time-wise. Hence, it makes sense to qualify whether a query is given as keywords (“digital initiative”) or as phrased questions (“What are the digital initiatives?”). In the case of <a href="https://www.deepset.ai/blog/save-resources-with-query-classifier-for-neural-search">keyword queries</a>, you might want to perform a regular document search instead of employing a full semantic search pipeline as it is faster.</p><p>Since we have fully phrased questions, we use a reader with a QA model:</p><pre><em># After having initialized our retriever, we initialize our reader<br></em>reader <strong>=</strong> FARMReader(<br>    model_name_or_path<strong>=&quot;</strong>deepset/roberta-base-squad2&quot;, use_gpu<strong>=False<br>    </strong>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xLJxhqvtbGBFhr81" /></figure><p>Finally, we add our building blocks together with a <em>Haystack Pipeline</em>. We use an <em>ExtractiveQAPipeline</em> that combines a retriever and a reader to answer our questions. Further pipelines can be found <a href="https://haystack.deepset.ai/docs/latest/pipelinesmd">here</a>. The python instruction is as simple as:</p><pre>pipe <strong>=</strong> ExtractiveQAPipeline(reader, retriever)<br>pipe.draw() # prints our pipeline</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/134/0*kCN6pfvc7EfIIAH0" /><figcaption>our extractiveQA pipeline</figcaption></figure><p>We are almost done! Now, we bring in Phil’s questions, so that our reader can use them to search in our documents. Mind that extractiveQA does well in searching for answers in large text corpora. Hence, questions should be phrase with question words (“What are efforts regarding digital experiences?”) rather than as yes/no questions (“Are efforts for digital experiences?”). If the question would be phrased so that the answer shall be yes or no, then a deep neural net has a hard time finding the correct answer in the documents (credits &amp; thanks to Tuana from deepset.ai!). Hence, we form the following questions:</p><pre>questions = [&quot;What are efforts regarding digital experiences?&quot;,<br>    &quot;What are the strategic priorities?&quot;,<br>    &quot;What is the company&#39;s growth?&quot;]</pre><p>We can configure how many candidates the reader and retriever returns for our questions. The higher the top_k for the retriever, the better (but also the slower) the answers. As a general rule, you might want to remember:</p><ul><li>If you are unhappy with the results: increase top_k_retriever.</li><li>If the system is too slow: lower the top_k_retriever.</li></ul><p>Here, we use an arbitrary top_k_retriever of 20:</p><pre>i = 0<br>for question in questions:<br>    prediction = pipe.run(query=question, params={&quot;Retriever&quot;: {&quot;top_k&quot;: 20}, &quot;Reader&quot;: {&quot;top_k&quot;: 5}})<br>    export_answers_to_csv(output_file=&quot;answers/result-&quot; + str(i) + &#39;.csv&#39;, agg_results=prediction)<br>    i += 1</pre><h3>The Results</h3><h4>Investigating the results</h4><p>We take a look at the results, and they are pretty breathtaking. You can go through Walmart’s <a href="https://corporate.walmart.com/media-library/document/2020-walmart-annual-report/_proxyDocument?id=00000171-a3ea-dfc0-af71-b3fea8490000">annual report</a> yourself, and identify the answers. Let us see what our extractiveQA pipeline gave us.</p><p>Question 1: What efforts are being made in regards to digital experiences?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mxIYYjZvUVGtTr2g_DBd5g.jpeg" /><figcaption>Answers to question 1 (actual answers marked in blue)</figcaption></figure><p>Question 2: What are strategic priorities?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eVXW60MS2ewRdwBONaywfA.jpeg" /><figcaption>Answers to question 2 (actual answers marked in blue)</figcaption></figure><p>Question 3: What is the company’s growth?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4b7oRJLfqtlKtKRZxbbveA.jpeg" /><figcaption>Answers to question 3 (actual answers marked in blue)</figcaption></figure><p>2 out of 3 questions were impressively correct. The last question was a numeric one, and quite tricky but Haystack found the right numbers for the international market. This is a solid base to start from, and can help Phil to contact the CMO of Walmart.</p><h4><strong>Evaluation of the results</strong></h4><p>If we would have used a deep neural net that we fine-tuned or trained ourselves, it would be a great time to <a href="https://www.deepset.ai/blog/how-to-evaluate-a-question-answering-system">evaluate</a> how good its performance is. Since we used a deep neural net out of the box this is not needed. <br>However, we would set up a test dataset, to understand if our efforts went well. Then, we would evaluate the retriever and the reader separately. For the retriever we would look into the recall score and for the reader we could use the F1 score and the semantic answer similarity (<a href="https://www.deepset.ai/blog/semantic-answer-similarity-to-evaluate-qa">SAS</a>).</p><h4>Interpretation of the results</h4><p>In general, current results are very good. They are a starter to look for the specifics in a given text (or extensive report), and the context allows us to understand them as a human. Personally, I am quite impressed.</p><p>The reader is very confident with the results of these questions as the confidence percentage is usually above 50% (you can see this if you run the accompanying code from the <a href="https://github.com/seduerr91/dpr_eqa/tree/main/">Github repo</a>).</p><p>There are still a myriad of ways on how to improve the situation for Phil, and to further advance his needs.</p><h3>Next Steps</h3><h4><strong>Avenues for improvements our neural search results</strong></h4><ul><li>Use a reader model that is trained or, at least, fine-tuned on 10-k, 10-q, financial reports. An example on how to do that can be found in <a href="https://colab.research.google.com/github/deepset-ai/haystack/blob/master/tutorials/Tutorial2_Finetune_a_model_on_your_data.ipynb">tutorial 2 by deepset.ai</a>.</li><li>Using knowledge distillation as explained <a href="https://www.deepset.ai/blog/knowledge-distillation-with-haystack">here</a>. We could transfer knowledge from a large model to a smaller model with fewer parameters to perform inference faster. Alternatively, we can improve the prediction quality of a model while retaining its size by <em>first</em> training a larger model and <em>then</em> distilling that model into the smaller model architecture of the original model.</li><li>Using different retrieval algorithms (sparse vs. dense) which is done in <a href="https://colab.research.google.com/github/deepset-ai/haystack/blob/master/tutorials/Tutorial1_Basic_QA_Pipeline.ipynb">tutorial 1 (sparse) by deepset.ai</a> and <a href="https://colab.research.google.com/github/deepset-ai/haystack/blob/master/tutorials/Tutorial6_Better_Retrieval_via_DPR.ipynb">tutorial 6 (dense) by deepset.ai</a>.</li><li>Since business reports often have tables, we could consider using models that are fine-tuned on tabular data like Google Tapas (as exemplarily done in <a href="https://colab.research.google.com/github/deepset-ai/haystack/blob/master/tutorials/Tutorial15_TableQA.ipynb">tutorial 15 by deepset.ai</a>).</li><li>We could further try to improve the phrasing of the questions by asking the same question in a variety of ways / paraphrasing the questions or using a deep neural net that helps with phrasing questions (e.g., via questions generation in <a href="https://colab.research.google.com/github/deepset-ai/haystack/blob/master/tutorials/Tutorial13_Question_generation.ipynb">tutorial 13 by deepset.ai</a>); explained <a href="https://www.deepset.ai/blog/generate-questions-automatically-for-faster-annotation">here</a>.</li><li>Also, next generation neural search techniques as in <a href="https://www.deepset.ai/blog/understanding-semantic-search">understanding semantic search</a> can help us.</li></ul><p><strong>Avenues for making our neural search accessible for Phil</strong></p><ul><li>Deploy this service as a microservice to a cloud platform &amp; expose it as a <a href="https://www.deepset.ai/blog/building-a-rest-api-for-question-answering-with-haystack">REST-API</a> or quickly build a prototype for Phil to interact with. The latter can be done with <a href="https://gradio.app/">Gradio</a> or <a href="https://streamlit.io/">Streamlit</a>.</li><li>Annotate the documents with any metadata that Phil may deem important as described in <a href="https://www.deepset.ai/blog/beyond-vanilla-question-answering-start-using-classification">Beyond Vanilla Question Answering</a>.</li><li>Consider re-ingesting qualified data to further fine-tune the model (<a href="https://namegenderpro.medium.com/how-to-build-a-dynamic-data-flywheel-from-ground-zero-with-marketing-hacking-6c998833d5b0">data flywheel</a>), to continuously improve the neural net and its outputs.</li></ul><h3>Summary</h3><p>Based on the business need of senior sales account executive Phil, we used the Haystack framework from deepset.ai to ask questions for querying annual financial reports from S&amp;P 500 company Walmart. The results of the DPR are pretty impressive. While they allow to scale massively, there are still aspects to be minded for humans in the loop:</p><ul><li>Based on the answers, the user has to be trained in how to ask questions in order to achieve his desired results.</li><li>Special care must be taken when defining the context of a question to ensure that the results are relevant.</li></ul><p>Since, I cannot fully identify what is most useful to the manager Phil, I am not further advancing my ‘question phrasing skills’ to score better in this very tutorial. Yet, I am amazed by the results.</p><h3>Thank you deepset.ai</h3><p>Thank you @deepset.ai for the wonderful tutorials that I used as a base for developing this business use case.</p><p><a href="https://github.com/seduerr91/dpr_eqa/blob/dcf5005bd1f3a3efe4a53dc490d74c3f98b0a7ef//deepset.ai">Deepset.ai</a> is an AI startup from Berlin. They are ‘building a semantic layer for the modern tech stack — driven by the latest NLP and open source.’ I was happy to go through their tutorials since I appreciate how clearly they are written. Special thanks to you Tuana for consulting me on how to phrase questions, and to Joy for helping me phrasing this article.</p><p>Thank you for reading this article and for any comments, Seb.</p><h3>Appendix</h3><p>Please find instructions to run this code locally and to fix bugs that occurred on my machine.</p><pre>## Dependencies to install on a Mac OS M1X chip.<br>## In order to run this script on my local machine, I had to download / install the following dependencies.</pre><pre>## Download &amp; install xpdf tools to process PDF documents with OCR<br># !wget --no-check-certificate <a href="https://dl.xpdfreader.com/xpdf-tools-mac-4.03.tar.gz">https://dl.xpdfreader.com/xpdf-tools-mac-4.03.tar.gz</a><br># !tar -xvf xpdf-tools-linux-4.03.tar.gz &amp;&amp; sudo cp xpdf-tools-mac-4.03/bin64/pdftotext /usr/local/bin<br>## Download &amp; install ocr (optical character recognition to read in pdfs with Python)<br># !pip install &#39;farm-haystack[ocr]&#39; -q</pre><pre>## Download &amp; install FAISS (i.e., Facebook AI Similarity Search, a library that allows developers to quickly search for embeddings of multimedia documents that are similar to each other.)<br># !pip install &#39;farm-haystack[faiss]&#39; -q<br>## Reduce the output of a nasty error models<br># import os<br># os.environ[&quot;TOKENIZERS_PARALLELISM&quot;] = &quot;false&quot;</pre><pre>## configuration to have nicer printing in pandas<br># pd.set_option(&#39;display.max_colwidth&#39;, None)</pre><pre>## Installing pygraphviz for pipe.draw() on Mac M1<br># brew install graphviz<br># python -m pip install \<br># --global-option=build_ext \<br># --global-option=&quot;-I$(brew --prefix graphviz)/include/&quot; \<br># --global-option=&quot;-L$(brew --prefix graphviz)/lib/&quot; \<br># pygraphviz</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e0cac743c7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What makes a message persuasive?]]></title>
            <link>https://medium.com/@duerr.sebastian/what-makes-a-message-persuasive-4c04322df929?source=rss-42e263a889aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c04322df929</guid>
            <category><![CDATA[persuasion]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[written-persuasion]]></category>
            <category><![CDATA[nlg]]></category>
            <dc:creator><![CDATA[Sebastian]]></dc:creator>
            <pubDate>Mon, 11 Oct 2021 11:28:24 GMT</pubDate>
            <atom:updated>2021-10-11T11:31:05.410Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Concept for Persuasiveness</h3><p>In persuasion, the persuader induces a particular kind of mental state in the persuadee, e.g., through threats, but unlike an expression of sentiment, persuasion intends a change in the mental state of the persuadee (Iyer &amp; Sycara 2019).</p><p>In the following, I conceptualize persuasive writing and embed it into a business context. Furthermore, I introduce related theories and present a categorization of a literature review that I conducted in Q4/2020. Contemporary psychology and communication science (Rocklage et al. 2018, Park et al. 2015, Hunter et al. 2019) require the persuader to be acting intentionally, that is, a persuasive act. In the context of NLG, we usually refer to messages generated or augmented by artificial intelligence, if we use the term persuasive act.</p><h3>Crossing Philosophic Ontologies and Business Approaches to Persuasion</h3><p>In his seminal work ‘On Rhetoric’, Aristotle introduced his well-known ontology for persuasive acts. Accordingly, persuasion depends on multiple facets: emotions (pathos), logical structure of the argument (logos), the context (cairos), and on the speaker (ethos) (Schiappa &amp; Nordin 2013). Likewise, contemporary business literature conceptualizes persuasive acts through “principles of persuasion” (DeMers 2016). The author concludes that six interventions help at achieving persuasiveness. The first is being confident and remaining confident during the entirety of an appeal. Next, the introduction of logical argumentation fosters persuasiveness, since individuals are more inclined to be persuaded by logic. Additionally, appealing seem beneficial to the other party, by demonstrating the value of an appeal, choosing words carefully (i.e., selecting from a vocabulary that may be more persuasive), and using flattery (i.e., finding appropriate compliments) are recommended. Lastly, DeMers (2016) reveals that being patient and persistent (i.e., not to greatly alter one’s approach) strengthens a persuader’s persuasiveness. Next, we embed the presented “principles of persuasion” into related theories on persuasion (Cameron 2009).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-xVRL2cedPfZSRjw.png" /><figcaption>A theoretical concept on written persuasion (cf. <a href="https://arxiv.org/abs/2101.05786">Duerr &amp; Gloor 2021</a>)</figcaption></figure><h4>Adding Theoretical Sugar to the Conceptualization</h4><h4>Cairos</h4><p>Festinger’s Theory of Cognitive Dissonance (1957) focuses on the relationships among cognitive elements, which include beliefs, opinions, attitudes, or knowledge (O’Keefe 1990). This relates mostly to Aristotle’s <strong>cairos</strong> as the need to create benevolence for the persuadee. Evaluating the ‘business principles’, this theory resonates best with what DeMers (2016) defines as ‘making [the cognition] appealing to the other party’. However cognitions, and thus, a persuadee’s perceived benevolence, can be dissonant, consonant, or irrelevant to each other. If a persuadee is presented with a sufficiently vast cognitive inconsistency, then they will perceive psychological discomfort, leading to an attempt to restore their cognitive balance through a reduction or elimination of the inconsistency (Stiff 1994, Harmon-Jones 2002). The magnitude of dissonance determines one’s motivation to reduce it (Stiff 1994, Festinger 1957). Approaches towards reducing dissonance are: changing terms to make them more consonant, adding additional consonant percipience, or altering the magnitude of the percipience (Harmon-Jones 2002, Stiff 1994, O’Keefe 1990).</p><h4><strong>Ethos</strong></h4><p>In ‘principles of persuasion’, DeMers (2016) contends that appropriate flattering and the usage of so-called high-value words contribute to persuasive acts in business contexts (cf. Aristotle’s <strong>ethos</strong>). Accordingly, Language Expectancy Theory (LET) identifies written or spoken language as a rule-based system through which persuadees develop expectations and preferences towards “appropriate” linguistic usage of words in varying situations (Burgoon &amp; Miller 1985). Such expectations are frequently consistent with sociological and cultural norms, while preferences tend to relate to societal standards and cultural values (Burgoon &amp; Miller 1985, Burgoon et al. 2002). Positive expectations that facilitate a persuasive act are, for instance, if a persuader stylizes a behavior that is perceived as more preferred than expected by the persuadee. In contrast, negative ones are inhibiting persuasion, e.g., when the persuader makes use of language that is considered to be socially unacceptable (Burgoon &amp; Miller 1985, Burgoon et al. 2002).</p><h4>Logos</h4><p>Next, the <em>principles of persuasion</em> confer that an argument based on logic is persuasive (DeMers 2016). What Aristotle terms <strong>logos</strong> is consistent with the theory of probabilistic models. Probabilistic models (McGuire 1981, Wyer 1970) are based on the rules of formal logic and probability and predict beliefs regarding the conclusion of reasoning. These predictions are based on mathematical probability, and as such, this theory is consistent with what Aristotle defines as logos. An exemplary belief syllogism (McGuire 1981) is composed of two premises that lead to a logical conclusion. The theorists (McGuire 1981, Wyer 1970) explain that believing in the premises leads to the expectation that the identified conclusion will follow. However, rather than solely thinking in all-or-nothing scenarios, beliefs can be ascertained through subjective probabilities: one’s judgment of the probability that each of the premises is true (McGuire 1981, Wyer 1970). Furthermore, if a message evokes a perceptual change in the truth of the premise, or additional premises are supplemented, following this theory, a change in perceiving the conclusion is expected.</p><h4>Pathos</h4><p>Last, Balance Theory focuses on the triadic relationship involving two individuals (e.g., persuader and persuadee), the persuadee’s attitude toward the persuader (Aristotle’s <strong>pathos</strong>), and their attitudes toward an attitudinal object (Heider 1958). The resulting triad can be balanced or unbalanced: This triad is in balance if all three relationships are positive, or one is positive and two are negative. If all three relationships are negative, or one is negative and two are positive, an unbalanced triad results, often motivating one to alter one of the three relationships (Heider 1958). Building on this theory, we aim to identify relational determinants that relate to improving the relationship between the persuader and the persuadee towards the attitudinal object (Heider 1958). In the business framework, we relate those determinants towards the pattern of ‘trustworthiness’, which represent the persuadee’s attitude towards the persuader. In his persuasion attempt, the persuader wants the persuadee to have a positive attitude.</p><h3>The Conceptualization of Persuasiveness in a Nutshell</h3><p>Starting from the increasing persuasiveness in business contexts, we adopt the ‘principles of persuasion’ (i.e., benevolence, linguistic appropriacy, logical argumentation, and trustworthiness), and embed them into different scholarly theories (i.e., balance theory, probabilistic models, theory of cognitive dissonance, and language expectation theory). However, since we regard persuasion also from a technical perspective, (i.e., natural language generation), we care about algorithms for measuring and changing a texts persuasiveness via natural language generation.</p><h3>Coming up: How do you measure persuasiveness?</h3><p>But how do you define written persuasiveness? Well, no one has ever done this. Therefore, we identified some sixty determinants that influence persuasiveness. Taking all of them into consideration is theoretically possible but practically not feasible. Yet, how can you?</p><h3>The good news</h3><p>We made textual persuasiveness measurable, and we will even provide the code for it! Stay tuned for the next blog article that explains how we get from persuasion theory to its implementation.</p><h4>Acknowledgements</h4><p>Thanks to my team at <a href="https://duerr.se/blog/persuai.de">Persuaide</a> where we working on technical persuasion.</p><h4>Who am I?</h4><p>I am Sebastian and an NLP Deep Learning Research Scientist. In my former life, I was a manager at Austria’s biggest bank. In the future, I want to work remotely whenever I want to &amp; in the field of NLP. Last year, I worked with MIT in Boston, and now we implement tools that improve communication for everybody.</p><p>Note: All presented references are listed in our <a href="https://arxiv.org/abs/2101.05786">literature review on NLG</a>.</p><h3>Thank you!</h3><p>Drop me a message on <a href="https://www.linkedin.com/in/sebastianduerr/">LinkedIn</a> if you want to get in touch or have any questions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c04322df929" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[4 Steps to Create Synthetic Datasets with T5, PAWS and Your Text Corpus]]></title>
            <link>https://medium.com/@duerr.sebastian/4-steps-to-create-synthetic-datasets-with-t5-paws-and-your-text-corpus-fc48bd9fc901?source=rss-42e263a889aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc48bd9fc901</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[t5]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[synthetic-data]]></category>
            <category><![CDATA[paraphrase]]></category>
            <dc:creator><![CDATA[Sebastian]]></dc:creator>
            <pubDate>Tue, 17 Nov 2020 15:59:48 GMT</pubDate>
            <atom:updated>2020-11-17T16:21:10.985Z</atom:updated>
            <content:encoded><![CDATA[<p>Does your organization train deep neural nets? Let me guess, data quality is a problem!</p><p>Read this article, to learn how to bring paraphrasing to Google’s T5, and then fine tuning it with custom textual data sets for synthetic dataset creation.</p><p><em>This is the Paraphrase Generator in action:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*uvSIqhOzRwNVUAssoFfyQA.gif" /><figcaption>Demo of Custom Paraphrasing Capability</figcaption></figure><p>Among the many challenges of supervised machine learning, the dependency on large labeled datasets ranks as the highest. Creating high-quality datasets is costly and difficult. This is even more accentuated for smaller organizations.</p><p>Fortunately, our generative method allows the generation of synthetic datasets that match the distribution of labeled datasets, making it possible to accelerate the training of machine learning models.</p><p>The process of creating such a fake data set is explained in the following four steps. Find the corresponding code in this <a href="https://github.com/seduerr91/synthetic_pub">Github Repository</a>.</p><h3>Step 1: Fine tune T5 with PAWS Data Set to Teach ‘paraphrase: ‘</h3><p>Since Google’s <a href="https://ai.googleblog.com/2020/02/exploring-transfer-learning-with-t5.html">T5</a> has been trained on multiple tasks (e.g., text summarization, sentence correctness — cola, and sentence similarity — stsb) solely through Text-to-Text tasks, it is handy for teaching it additional capabilities. We taught T5 via fine tuning it with the <a href="https://github.com/google-research-datasets/paws">PAWS dataset</a>. The PAWS dataset consists of approximately 50.000 labeled paraphrases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*GpBupFh00IG0qfp9555Jyw.jpeg" /><figcaption>Step 1: Fine tune T5 on the PAWS Dataset (Icon Credits to FreePik)</figcaption></figure><p>After that, we resulted in a T5-P(araphrase) model which can create paraphrases from texts without a specific context. However, this one is not optimally suited for our business journal context. Hence, we used a text corpus to make its paraphrases sound more <em>biz</em>.</p><h3>Step 2: Use T5-P with Custom Data to Create Synthetic Data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*7SCJ5ycC2m1MGgj4fJUdnQ.jpeg" /><figcaption>Step 2: Use T5-P for Creating a Custom Dataset (Icon Credits to FreePik)</figcaption></figure><p>As a next step, we use our custom data (i.e., a business text corpus) to create paraphrases with our new capability of T5-P(araphrase), i.e. <strong>paraphrasing</strong>. Although we only have a small corpus (330 samples), we use these to create a data set from it.</p><p>This resulting synthetic data set has the original 330 samples in the first column, and the created paraphrases in a second column.</p><h3>Step 3: Use T5 to Ensure Synthetic Data’s Syntactical &amp; Semantical Quality</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*XyBt47eEyZxqLa4O-1zoxg.jpeg" /><figcaption>Step 3: Use T5-P To Ensure Data Set Quality (Icon Credits to FreePik)</figcaption></figure><p>Before, using our T5-P to create business paraphrases, we want to ensure that we only fine tune it with semantically congruent and syntactically correct paraphrases. Hence, we have to evaluate our newly created synthetic data set.</p><p>Evaluation techniques like ROUGE and BLEU are not useful in our context since they look for similar words. Obviously, paraphrases are better if they use different words to communicate the same.</p><p>Therefore, we use a trick: Google’s T5 is trained for similarity (feature: ‘stsb sentence 1: […]sentence2: […]) which we can use to ensure that our original sentence and its corresponding paraphrase have the same semantic meaning. <em>In our project, 95% of sentences had a similarity score above 4.0 which we considered further</em>).</p><p>Yet, our sentences could still be syntactically incorrect. Hence, we also evaluated that with a toolkit of T5. Checking for syntactical correctness is being done by using ‘cola: [‘sentence’]’ which we applied to the synthetic paraphrases. <em>Only three out of 313 samples were not accepted.</em></p><h3>Step 4: Fine tune T5-P with Qualified Synthetic Data for Custom Paraphrases</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*NSJJNwtZXbLGsq1SmyinwA.jpeg" /><figcaption>Step 4: Fine-tune T5-P to Write Custom Paraphrases (Icon Credits to FreePik)</figcaption></figure><p>Finally, we fine tune our T5-P(araphrase) model with our synthetically created data set (that is both syntactically and semantically correct). After that, we can create very authentic paraphrases resembling our business corpus. You can use this <a href="https://github.com/seduerr91/pawraphrase_public/blob/master/t5_pawraphrase_inference.ipynb">Colab</a> for inference to create your own.</p><h3>(Optional) Using the fine-tuning through a GUI or FastAPI</h3><p>If you’d like to make your service interactive, you can provide it as a <a href="https://github.com/renatoviolin/T5-paraphrase-generation">flask frontend</a> which was adapted from the works of Renato (Kudos!). Alternatively, you can access it via an API call through FastAPI <a href="https://seduerr91.github.io/blog/ilm-fastapi">(find a how to here)</a></p><p>Thank you for reading this article. I am curious about your opinion.</p><h4>Hi there! I want to work in NLP.</h4><p>I am Sebastian (M.Sc. in IT /Business) an NLP Deep Learning Engineer. I help organizations to use artificial intelligence with natural language processing.</p><p>In my former life, I was a manager at Austria’s biggest banking group. In the future, I want to work remotely flexibly &amp; in the field of NLP.</p><p><a href="https://www.linkedin.com/in/sebastianduerr/">Contact me</a> to get in touch!</p><h3>Kudos to Narrativa.com</h3><p>This service was created in cooperation with <a href="http://ww.narrativa.com/">Narrativa.com</a>, a Spanish deep learning company, that helps companies to create texts with the help of AI. Javier García Ortíz (Chief Scientist) was leading the project from Narrativa’s side.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc48bd9fc901" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hosting your text generating infilling micro-service with FastAPI on GCP]]></title>
            <link>https://medium.com/analytics-vidhya/hosting-your-text-generating-infilling-micro-service-with-fastapi-on-gcp-ecf92f9d3c0f?source=rss-42e263a889aa------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecf92f9d3c0f</guid>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[infilling]]></category>
            <category><![CDATA[gpt-2]]></category>
            <category><![CDATA[fastapi]]></category>
            <dc:creator><![CDATA[Sebastian]]></dc:creator>
            <pubDate>Tue, 06 Oct 2020 08:44:51 GMT</pubDate>
            <atom:updated>2020-10-21T17:11:36.078Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hosting your Text Generating Infilling Micro-Service with FastAPI on GCP</h3><p>This micro-service allows the artificially generated infilling of multiple words into a context. Researchers from Stanford addressed this. I made their work available through an Application Programming Interface (API).</p><p>The following article explains how to implement a NLP architecture trained for infilling. It generates different infilling texts for a given context. This article is structured into a demo of the model, an explanation how to deploy it, and a quick dive into the underlying code concepts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F2NBx6H_xVeCI7mt2ZyWLw.png" /><figcaption>Auto-generated infilling by the deep neural net. These are suggestions for the _ slot.</figcaption></figure><h3>1. Testing the Infilling Micro-Service</h3><p>With this micro-service, you can generate infilling into a specific context by simply adding a ‘_’-token. Such an infilling can be done with words, n-grams (multiple words), or sentences.</p><blockquote>Text infilling is the task of predicting missing spans of text which are consistent with the preceding and subsequent text.</blockquote><p>This micro-service is based on the Infilling Language Model (ILM) framework which was outlined in the ACL 2020 paper E<a href="https://arxiv.org/abs/2005.05339">nabling language models to fill in the blanks</a> by Donahue et al. (2020).</p><p>- If you want to test the infilling model, go ahead and click <a href="https://ilmapi.uc.r.appspot.com/docs">here</a>.</p><p>- A guide on how to use this service can be found <a href="https://seduerr91.github.io/blog/ilmapi-instructions">here</a>.</p><p>- The git repository with the source code is stored <a href="https://github.com/seduerr91/ilm-api">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vVM6E3MOiuL3kfUq8QCRyw.png" /><figcaption>This is how this Micro-Service looks. You can try it out right there!</figcaption></figure><h3>2. Deploying Your Own Infilling Micro-Service on Google Cloud Platform</h3><p>In order to deploy your own infilling micro-service just follow the next simple seven steps.</p><p>1. To deploy this micro-service by yourself please create a new project on <a href="https://cloud.google.com/">Google Cloud Platform</a> (GCP). For the new project to be created, you have to choose a <em>project name</em>, <em>project ID</em>, <em>billing account</em>, and, then, to click <em>Create</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q5AxdPmAtpZ10x5XsoyQqQ.png" /><figcaption>Start a NEW PROJECT.</figcaption></figure><p>2. Next, activate Google’s <em>Cloud Shell</em> in the upper right corner of GCP to execute a few lines of code to host the ILM-API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hmmjxo0O5MXJDy98qcelYA.png" /><figcaption>Activate the Cloud Shell.</figcaption></figure><p>3. Now, we clone the <a href="https://github.com/seduerr91/ilm-api">ILM-API Repository</a> from GitHub. Fort that, type the following command into the Cloud Shell:</p><p><strong>git clone </strong><a href="https://github.com/seduerr91/ilm-api.git"><strong>https://github.com/seduerr91/ilm-api.git</strong></a></p><p>4. As a next step, we install the requirements. These project related libraries are located in the file <em>requirements.txt.</em> To install all these modules in one go, run the following command:</p><p><strong>pip3 install -r requirements.txt</strong></p><p>5. To prepare for the deployment of the FastAPI micro-service on Google App Engine, we need to create a gcloud app. Note: By executing the next command, you will be prompted to select a region. Simply choose the region nearest to the geographical location where your consumers access this micro-service. In the cloud shell, type the following command to create the app:</p><p><strong>gcloud app create</strong></p><p>6. <em>You are almost there</em>! Now, we actually deploy the FastAPI app on GCP App Engine. While running the next command in the shell, you will be prompted to continue. Press Y and hit enter to proceed. It takes a few moments to host the service (like 3–5 minutes), once you execute:</p><p><strong>gcloud app deploy app.yaml</strong></p><p>7. Now, you can browse to your micro-service. Generally, your app is deployed on the URL that has the following format: your-project-id.appspot.com. In case, you are not sure what the project id is, then type the following command to view your application in the web browser:</p><p><strong>gcloud app browse</strong></p><h4>Congratulations! You just hosted the your own infilling micro-service based on the Deep Neural Architecture GPT-2 via FastAPI.</h4><p>Next, we take a brief look at the source code, to better understand what we just did.</p><h3>3. Remarks About the Code Files</h3><p>The source code of the micro-service majorly consists of the infilling model, and the following files presented hereafter.</p><h4>infill.py</h4><p>The inference method is wrapped into the ‘class Infiller()’ which we need for the API in ‘main.py’. This loads the data model, sets an exemplary context, appends the specific tokens to the context file, and, runs the inference to generate the infilling sentences.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df9eeb47867ff2b04b312e94e93a6f4c/href">https://medium.com/media/df9eeb47867ff2b04b312e94e93a6f4c/href</a></iframe><h4>main.py</h4><p>We serve the uvicorn server through the main.py file via ‘uvicorn main:app’. This hosts the POST APIs for the server queries.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d69008203b76a27cc452a41b6b529c7/href">https://medium.com/media/3d69008203b76a27cc452a41b6b529c7/href</a></iframe><h4>requirements.txt</h4><p>The requirements.txt is very brief but it installs all required dependencies. In this example torch (PyTorch) is being used but you can also use Tensorflow if this is your preference.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40f816943aaa070c1083933ed764b552/href">https://medium.com/media/40f816943aaa070c1083933ed764b552/href</a></iframe><h4>app.yaml</h4><p>Google Cloud Platform allows the App Engine to perform deployment based on a configuration defined in a YAML file. For us to host the FastAPI on Google App Engine, the YAML configuration needs to have the following configuration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eaa2a2999d57b2fa543f1fcac6fcb8b2/href">https://medium.com/media/eaa2a2999d57b2fa543f1fcac6fcb8b2/href</a></iframe><h4>Dockerfile</h4><p>The Dockerfile is being executed via the app.yaml. It hosts a Python3.7 container, copies the app’s source code, installs the requirements needed, and executes the main app.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ffb6d1411e5584b36ee4745c8aa6c94/href">https://medium.com/media/1ffb6d1411e5584b36ee4745c8aa6c94/href</a></iframe><h3>Resources</h3><p>This micro-service is build on the shoulders of the following giants:</p><p>- <a href="https://github.com/chrisdonahue/ilm">Git Infilling by Language Modeling (ILM)</a></p><p>- <a href="https://huggingface.co/transformers/main_classes/pipelines.html">HuggingFace Pipeline</a></p><p>- <a href="https://www.tutlinks.com/deploy-fastapi-app-on-google-cloud-platform/">Deploy FastAPI App on Google Cloud Platform</a></p><p>- <a href="https://towardsdatascience.com/build-and-host-fast-data-science-applications-using-fastapi-823be8a1d6a0">Build And Host Fast Data Science Applications Using FastAPI</a></p><p>- <a href="https://chatbotslife.com/deploying-transformer-models-1350876016f">Deploying Transformer Models</a></p><p>- <a href="https://towardsdatascience.com/how-to-properly-ship-and-deploy-your-machine-learning-model-8a8664b763c4">How to properly ship and deploy your machine learning model</a></p><p>- <a href="https://docs.python.org/3/tutorial/venv.html">Setting Up Virtual Environments</a></p><h3>Acknowledgements</h3><p>Thanks to Javier and the team of <a href="http://narrativa.com/">Narrativa</a> that asked me to host the micro-service. Also, a big thanks to <a href="http://huggingface.co/">HuggingFace</a>, the Team from Stanford around Mr. Donahue. Also, thanks to <a href="http://wifitribe.co/">WifiTribe</a> with which I am currently living as a Digital Nomad. It is a very amazing bunch of people. I am doing my research and education remotely.</p><h4>Who am I?</h4><p>I am Sebastian an NLP Deep Learning Research Scientist. In my former life, I was a manager at Austria’s biggest bank. I like to work in on NLP problems.</p><p>Drop me a <a href="https://www.linkedin.com/in/sebastianduerr/">message</a> if you want to get in touch or have any questions. Thank you for giving me your opinion.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecf92f9d3c0f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/hosting-your-text-generating-infilling-micro-service-with-fastapi-on-gcp-ecf92f9d3c0f">Hosting your text generating infilling micro-service with FastAPI on GCP</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>