<?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 Daniel Melchor on Medium]]></title>
        <description><![CDATA[Stories by Daniel Melchor on Medium]]></description>
        <link>https://medium.com/@danielmelchor?source=rss-c155441b01d9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yvFHbbu3VDPe_vsyt0h2vA.jpeg</url>
            <title>Stories by Daniel Melchor on Medium</title>
            <link>https://medium.com/@danielmelchor?source=rss-c155441b01d9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 02:32:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@danielmelchor/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[Q&A Models for specific information extraction]]></title>
            <link>https://medium.com/data-science/q-a-models-for-specific-information-extraction-2a204f7f3521?source=rss-c155441b01d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/2a204f7f3521</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[bert]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Daniel Melchor]]></dc:creator>
            <pubDate>Wed, 21 Jul 2021 12:27:02 GMT</pubDate>
            <atom:updated>2021-07-21T12:27:02.762Z</atom:updated>
            <content:encoded><![CDATA[<h4>The power of transformers for obtaining relevant entity extraction from unstructured texts</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*N3miu27UYjpLucoadBkGfg.png" /><figcaption>Image by author</figcaption></figure><p>121 a day, 3,751 a month, and 44,165 a year. According to <a href="https://www.campaignmonitor.com/resources/knowledge-base/how-many-emails-does-the-average-person-receive-per-day/#:~:text=Keeping%20all%20this%20in%20mind,will%20be%20closer%20to%20126.">some calculations</a>, that is the number of emails the average person receives. I don’t know about you, but for me, that is a lot of emails to give my time to…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*OC84u7HFC9Pan6nuVD8Wnw.png" /><figcaption>Image by author</figcaption></figure><p>Wouldn’t it be nice if you could immediately classify them depending on what the email is about, if they are trying to sell something, if you have to contact someone back, etc.? I have put to the test some traditional information extraction techniques as well as a more innovative (and quite powerful) technique. Here is a summary of how they work and the different results.</p><h3>The example email</h3><p>For the sake of being consistent we will use the following example email (mostly generated using GPT-3) to compare and observe the different current solutions to this problem:</p><blockquote>Hi Jack,</blockquote><blockquote>I’m sorry, I’ve been distracted by my new Tesla car company, and I’m afraid I’m going to have to delegate the leadership of the bitcoin project to someone else.</blockquote><blockquote>I need someone really really skilled. Could you advise me on who to appoint? Elon Musk is too busy already!</blockquote><blockquote>Many thanks,</blockquote><blockquote>Sat.</blockquote><blockquote>P.S.: I’ve got a Tesla Roadster too!</blockquote><blockquote>—</blockquote><blockquote>Satoshi Nakamoto</blockquote><blockquote>Phone number: +1 (650) 566–1191</blockquote><blockquote>Bitcoin: 1GttzecjYm19xu3iC8i8NEuM7mB5uZQbKD</blockquote><p>If you are curious, the input given to GPT-3 was: “<em>This is an email from Satoshi Nakamoto to Jack explaining how the bitcoin network seems to have disconnected. The email:”. </em>The result isn’t really related but it works just fine as an example.</p><h3>Techniques</h3><h4>Option 1: Regular expressions</h4><p>The oldest solution to the information extraction problem is regular expressions. We can use these to extract from a text the strings that match a certain pattern. For simplicity, we are going to only be extracting the name of who we should contact back (in many cases it is not the name of the person who sent the email).</p><p>Let’s begin by assuming that a full name can follow these formats:</p><pre>Satoshi Nakamoto</pre><pre>Satoshi K. Nakamoto</pre><pre>Satoshi K Nakamoto</pre><pre>Satoshi Nakamoto-Koa</pre><pre>Satoshi Nakamoto Koa</pre><p>So a possible regex expression could be:</p><pre>(?:[A-Z][a-z]+)+(?:[\- ][A-Z](?:[a-z\.]+)?)+</pre><p>Getting all the matches from the email with regex would look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4cc91ac994519908c395250971e4d25/href">https://medium.com/media/b4cc91ac994519908c395250971e4d25/href</a></iframe><p>Which would select the following strings from our email:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*_GSEcHS1VzL1-CvWz7Td6w.png" /><figcaption>Regex extraction: Image by author</figcaption></figure><p>As you can see, this method is good to lower the number of options to choose from, but we still get <strong>strings that aren’t names</strong> and we don’t have an efficient way of identifying the important one (we can’t just always pick the last one).</p><h4>Option 2: Using entity detection</h4><p>A common way to fix the previous issue (detecting strings that aren’t names) is using <a href="https://spacy.io/">spaCy</a>.</p><blockquote>spaCy is an open-source software library for advanced natural language processing, written in the programming languages Python and Cython.</blockquote><p>spaCy will allow us to quickly set up an entity detector model, that will hopefully help us extract the information we want from the email. To download your preferred model you need to run:</p><pre>python -m spacy download &lt;MODELNAME&gt;</pre><p>And since we are going to use spaCy 3.1’s transformer model, we need to run:</p><pre>python -m spacy download en_core_web_trf</pre><p>The full code for this looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0afb5a7c4633f01e1a31042aa265271/href">https://medium.com/media/d0afb5a7c4633f01e1a31042aa265271/href</a></iframe><p>Which would select the following from our email:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*BUlrrbbj2Y57vBJgyXCXDg.png" /><figcaption>spaCy extraction: Image by author</figcaption></figure><p>As you can see, this model did much better than regex. It ignored cases like “<em>Tesla Roadster</em>” or “<em>Hi Jack</em>”, but it didn’t get the correct name: <em>“Satoshi Nakamoto”</em>! This is likely due to spaCy never encountering this name before inside its training data.</p><p>This doesn’t really change the outcome though… Even if spaCy had detected <em>“Satoshi Nakamoto”</em> we still wouldn’t know which of the person entities is the important one.</p><p>How can we do it? Is it even possible? So many questions! Mmmm… questions. What if we just ask the computer which name is the important one?! Let’s try that.</p><p><strong>Option 3A: Q&amp;A Transformer models</strong></p><p>Using a transformer that has been fine-tuned with a question-answering dataset like <a href="https://rajpurkar.github.io/SQuAD-explorer/">SQuAD</a> will allow us to ask it any question about the context it receives (in this case the email).</p><p>Thankfully, the <a href="http://huggingface.co/">HuggingFace</a> library includes lots of pre-trained models ready to be used out of the box. For simplicity, we will be using one of these, since not everyone can afford a TPU ready-to-train models as big as BERT. Feel free to take a look at their model catalog and choose the model that you like the most. I will use the <em>“</em><a href="https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad">bert-large-uncased-whole-word-masking-finetuned-squad</a><em>” </em>model which, according to them, achieves an F1 score of 93.15.</p><p>Like spaCy, HuggingFace has an API that allows users to quickly interact with the pre-trained models for specific tasks: <a href="https://huggingface.co/transformers/main_classes/pipelines.html">pipelines</a>.</p><p>Before we do that, we first need to know which questions to ask. Here are the five questions I could think of to ask the model:</p><ul><li>What is his name?</li><li>What is her name?</li><li>What is their name?</li><li>Who sent this?</li><li>What is the name of the person who sent this?</li></ul><p>Now that we have our questions, our code looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f12887a8822d8baa45beecc0c6c69adb/href">https://medium.com/media/f12887a8822d8baa45beecc0c6c69adb/href</a></iframe><p>Which outputs the following probabilities for each answer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*vNeUffP4dDsUhcyglAZ41w.png" /><figcaption>Q&amp;A Model extraction: Image by author</figcaption></figure><p><em>“Tesla car company”</em>, <em>“Satoshi”</em> and <em>“Tesla”</em>? Here we have a similar problem to regex-only extraction (Option 1): we get formats that don’t look like the ones we want, and entities that are not a name.</p><p>To solve this we have three options: we can use regex, spaCy, or both. Since we have already seen that spaCy couldn’t detect the name <em>“Satoshi Nakamoto” </em>as a person, we are going to use regex. You should try using spaCy instead since it will also be useful in other scenarios. If you are feeling adventurous, try both at the same time.</p><p><strong>Option 3B: Q&amp;A Transformer models + regex filtering</strong></p><p>Adding the filtering step we saw in Option 1 we get:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6c65a11994d8db2321f384b7488142b/href">https://medium.com/media/a6c65a11994d8db2321f384b7488142b/href</a></iframe><p>If we run this code we get these new probabilities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*qNprZntDK8nrxFQdNHsr-A.png" /><figcaption>Q&amp;A Model extraction + Regex: Image by author</figcaption></figure><h3>Results</h3><p>And there we go! Thinking out of the box we were able to extract relevant information from a text. Think about it: if you have a question about the email, just ask the computer! ;)</p><p>Here are other questions I asked the model that I found interesting. Try your own questions and see what answer the model gives you, but remember to remove/change the regex checking if it&#39;s not about names!</p><pre>Q: What is his phone number?<br>A: +1 (650) 566–1191 -- 91.74% Sure</pre><pre>Q: What does he need?<br>A: someone really really skilled -- 42.43% Sure</pre><pre>Q: What is his bitcoin wallet address?<br>A: 1GttzecjYm19xu3iC8i8NEuM7mB5uZQbKD -- 1.72% Sure</pre><pre>Q: What car does he have?<br>A: Tesla Roadster -- 75.22% Sure</pre><pre>Q: Who doesn&#39;t have time?<br>A: Elon Musk -- 95.99% Sure</pre><h3>Conclusion</h3><p>Trying non-traditional methods can sometimes give you better results! Even though there are datasets to extract relevant information like the <a href="https://www.cs.cmu.edu/~einat/datasets.html">Enron person name annotations dataset</a>, none of them contain enough information to be used for this purpose.</p><p>I am excited to see what the future holds for the machine learning community and how some of these super-powerful models are used for everyday purposes.</p><p><strong>Full Colab Notebook</strong>: <a href="https://colab.research.google.com/drive/1nCTYA2QWxov77GzBFuA9nndv3QUZInns?usp=sharing">https://colab.research.google.com/drive/1nCTYA2QWxov77GzBFuA9nndv3QUZInns?usp=sharing</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a204f7f3521" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/q-a-models-for-specific-information-extraction-2a204f7f3521">Q&amp;A Models for specific information extraction</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A detailed guide to Pytorch’s nn.Transformer() module.]]></title>
            <link>https://medium.com/data-science/a-detailed-guide-to-pytorchs-nn-transformer-module-c80afbc9ffb1?source=rss-c155441b01d9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c80afbc9ffb1</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Daniel Melchor]]></dc:creator>
            <pubDate>Thu, 08 Jul 2021 21:20:51 GMT</pubDate>
            <atom:updated>2021-07-10T22:55:14.537Z</atom:updated>
            <content:encoded><![CDATA[<h3>A detailed guide to PyTorch’s nn.Transformer() module.</h3><h4>A step-by-step guide to fully understand how to implement, train, and infer the innovative transformer model.</h4><p>I have recently been getting more involved in the world of machine learning. When I’ve had a problem understanding a complex issue or coding a neural network, the internet has seemed to have all the answers: from a simple linear regression to complex convolutional networks. At least that is what I thought…</p><p>Once I began getting better at this Deep Learning thing, I stumbled upon the all-glorious transformer. The original paper: “<a href="https://arxiv.org/abs/1706.03762">Attention is all you need</a>”, proposed an innovative way to construct neural networks. No more convolutions! The paper proposes an encoder-decoder neural network made up of repeated encoder and decoder blocks. The structure is the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/0*9AyLObnUZmIlLy5a.png" /><figcaption>Transformer structure: <a href="https://arxiv.org/abs/1706.03762">https://arxiv.org/abs/1706.03762</a></figcaption></figure><p>The left block is the encoder, and the right block is the decoder. If you don’t understand the parts of this model yet, I highly recommend going over Harvard’s “<a href="https://nlp.seas.harvard.edu/2018/04/03/attention.html">The Annotated Transformer</a>” guide where they code the transformer model in PyTorch <strong>from scratch</strong>. I will not be covering important concepts like “multi-head attention” or “feed-forward layers” in this tutorial, so you should know them before you continue reading. If you have already taken a look at the code from scratch, you are probably wondering if you are going to have to copy-paste that code all over the place for every project you make. Thankfully, <strong>no</strong>. Modern python libraries like PyTorch and <a href="https://www.tensorflow.org/">Tensorflow</a> already include easily accessible transformer models through an import. However, there is more to it than just importing the model and plugging it in. Today I will explain how to use and tune PyTorch <em>nn.Transformer()</em> module. I personally struggled trying to find information about how to implement, train, and infer from it, so I decided to create my own guide for all of you.</p><h3>First steps</h3><h4>Imports</h4><p>To start, we need to import PyTorch and some other libraries we are going to be using:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea124579d8707a3ffeb6e231c2374c2b/href">https://medium.com/media/ea124579d8707a3ffeb6e231c2374c2b/href</a></iframe><h4>Basic transformer structure</h4><p>Now, let’s take a closer look at the transformer module. I recommend starting by reading over <a href="https://pytorch.org/docs/stable/generated/torch.nn.Transformer.html#torch.nn.Transformer">PyTorch’s documentation about it</a>. As they explain, there are no mandatory parameters. The module comes with the “Attention is all you need” model hyperparameters. To use it, let’s begin by creating a simple PyTorch model. I will only change some of the default parameters so our model doesn’t take unnecessarily long to train. I made those parameters part of our class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4428b3f8a76a563f83912965a221eef3/href">https://medium.com/media/4428b3f8a76a563f83912965a221eef3/href</a></iframe><h4>Positional encoding</h4><p>The transformer blocks don’t care about the order of the input sequence. This, of course, is a problem. Saying “I ate a pizza with pineapple” is not the same as saying “a pineapple ate I with pizza”. Thankfully, we have a solution: positional encoding. This is a way to “give importance” to elements depending on their position. A detailed explanation of how it works can be found <a href="https://kazemnejad.com/blog/transformer_architecture_positional_encoding/">here</a>, but a quick explanation is that we create a vector for each element representing its position with regard to every other element in the sequence. Positional encoding follows this very complicated-looking formula which, in practice, we won’t really need to understand:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WDeWlMbeFO9KCZWi.png" /><figcaption>Positional Encoding Formula: Image by author</figcaption></figure><p>For the sake of organization and reusability, let’s create a separate class for the positional encoding layer (it looks hard but it is really just the formula, dropout, and a <a href="https://towardsdatascience.com/residual-blocks-building-blocks-of-resnet-fd90ca15d6ec">residual connection</a>):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3cfada18a4487ae11ab812ed5d8446d/href">https://medium.com/media/b3cfada18a4487ae11ab812ed5d8446d/href</a></iframe><h3>Completing our model</h3><p>Now that we have the only layer not included in PyTorch, we are ready to finish our model. Before adding the positional encoding, we need an <a href="https://pytorch.org/docs/stable/generated/torch.nn.Embedding.html">embedding layer</a> so that each element in our sequences is converted into a vector we can manipulate (instead of a fixed integer). We will also need a final linear layer so that we can convert the model’s output into the dimensions of our desired output. The final model should look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1fe4af56a75b84eba863de404c800e7/href">https://medium.com/media/d1fe4af56a75b84eba863de404c800e7/href</a></iframe><p>I know… It looks very intimidating, but if you understand what each part does, it is actually a pretty simple model to implement.</p><h4>Refreshing some important information: target masking</h4><p>You may recall there was a special block in the model structure called “<strong>masked</strong> multi-head attention”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*HZnY5vV9JDJGItRargn-TQ.png" /><figcaption>Masked Multi-head Attention: <a href="https://arxiv.org/abs/1706.03762">https://arxiv.org/abs/1706.03762</a></figcaption></figure><p>So… what is masking? Before I can explain it to you, let’s quickly recapitulate what is going on with our tensors when we feed them into our model. First, we embed and encode (positional encoding) our <strong>source</strong> tensor. Then, our source tensor is encoded into an unintelligible encoded tensor that we feed into our <strong>decoder</strong> with our embedded and encoded (positionally) <strong>target</strong> vector. For our model to learn, we can’t just show it the whole target tensor! This would just give him the answer straight up.</p><p>The solution to this is a masking tensor. This tensor is made up of size (sequence length x sequence length) since for every element in the sequence, we show the model one more element. This matrix will be added to our target vector, so the matrix will be made up of zeros in the positions where the transformer can have access to the elements, and minus infinity where it can’t. An illustrated explanation might help you a bit more:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*UJlsQ-JvWhCd_2tqdhK2hw.png" /><figcaption>Target Vector Masking: Image by author</figcaption></figure><h4>Refreshing some important information: padding masking</h4><p>In case you didn’t know, tensors are matrices that can be stored in a GPU, and since they are matrices, all dimensions must have elements of the same size. Of course, this won’t happen when treating with tasks like NLP or different-sized images. Therefore, we use the so-called “<strong>special tokens</strong>”. These tokens allow our model to know where the start of the sentence is (&lt;SOS&gt;), where the end of the sentence is (&lt;EOS&gt;) and what elements are just there to fill up the remaining space so that our matrices have the sam sequence size (&lt;PAD&gt;). These tokens must also be converted into their corresponding integer id (In our example they will be 2, 3, and 4 respectively). Padding a sequence looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*wBrLXpvJJvDG94nxuoOhJg.png" /><figcaption>Padding a batch of sequences: Image by author</figcaption></figure><p>To tell our model that these tokens should be irrelevant, we use a binary matrix where there is a <em>True</em> value on the positions where the padding token is and <em>False</em> where it isn’t:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dneSPVcOvjxj0wfi.png" /><figcaption>Padding mask: Image by author</figcaption></figure><h4>Creating the masking methods</h4><p>To create the two masking matrices we talked about, we need to extend our transformer model. If you know a bit of NumPy, you will have no problem understanding what these methods do. If you can’t understand it, I recommend opening a <a href="https://jupyter.org/">Jupyter notebook</a> and going step by step to understand what they do.</p><p>The full extended model looks like this (note the change in the forward method as well):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd65284c90eb1ada1f1cca7909ec00bb/href">https://medium.com/media/bd65284c90eb1ada1f1cca7909ec00bb/href</a></iframe><h3>Getting our data</h3><p>For the sake of this project, I am going to create a set of fake data we can use to train our model. This data will be made up of sequences like:</p><ul><li>1, 1, 1, 1, 1, 1, 1, 1 → 1, 1, 1, 1, 1, 1, 1, 1</li><li>0, 0, 0, 0, 0, 0, 0, 0 → 0, 0, 0, 0, 0, 0, 0, 0</li><li>1, 0, 1, 0, 1, 0, 1, 0 → 1, 0, 1, 0, 1, 0, 1, 0</li><li>0, 1, 0, 1, 0, 1, 0, 1 → 0, 1, 0, 1, 0, 1, 0, 1</li></ul><p>Feel free to skip to the next section if you aren’t interested in the data creation part.</p><p>I won’t bother explaining what these functions do since they are pretty easy to understand with basic NumPy knowledge. I’ll create all the sentences of size 8 so I don’t need padding, and I’ll organize them randomly into batches of size 16:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f68f17cfc8e51d7870bcb5a2843620b7/href">https://medium.com/media/f68f17cfc8e51d7870bcb5a2843620b7/href</a></iframe><h3>Training &amp; Validation</h3><h4>Training</h4><p>Now that we have data to work with, we can get to training our model. Let’s begin by creating an instance of our model, loss function, and optimizer. We will use the <a href="https://pytorch.org/docs/stable/generated/torch.optim.SGD.html">Stochastic Gradient Descent optimizer</a>, the <a href="https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html">Cross-Entropy Loss function</a>, and a learning rate of 0.01. I will also use my graphics card for this training since it will take less time, but it is not necessary.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/435a1c9a9ea9ff51ee844be385ec4456/href">https://medium.com/media/435a1c9a9ea9ff51ee844be385ec4456/href</a></iframe><p>An important concept we need to understand before continuing is that the target tensor we give as an input to the transformer must be shifted by one to the right (compared to the target output tensor). In other words, the tensor we want to give the model for training must have one extra element at the beginning and one less element at the end, and the tensor we compute the loss function with must be shifted in the other direction. This is so that if we give the model an element during inference, it gives us the next one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*87DnBur3EX5XL3SGGt-gRA.png" /><figcaption>Target vector shifting: Image by author</figcaption></figure><p>Now that we have grasped this concept, let’s get to coding! The training loop is a standard training loop except:</p><ul><li>The target tensor is passed to the model during the prediction</li><li>A target mask is generated to hide the next words</li><li>A padding mask might be generated and passed to the model as well</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de3dbcd64bf52304a81cb22bb25393b0/href">https://medium.com/media/de3dbcd64bf52304a81cb22bb25393b0/href</a></iframe><h4>Validation</h4><p>The validation loop is exactly the same as our training loop except we don’t read or update gradients:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebff4ce039d4789e67850255cf2614c1/href">https://medium.com/media/ebff4ce039d4789e67850255cf2614c1/href</a></iframe><h4>Executing the training and validation</h4><p>In this example, I am training the model for 10 epochs. To simplify the training I created a fit function that calls the train and validation loop every epoch and prints the loss:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce016b47caf60e846375fa164120662b/href">https://medium.com/media/ce016b47caf60e846375fa164120662b/href</a></iframe><p>This produces the following out</p><pre>Training and validating model<br>------------------------- Epoch 1 -------------------------<br>Training loss: 0.5878<br>Validation loss: 0.4172</pre><pre>------------------------- Epoch 2 -------------------------<br>Training loss: 0.4384<br>Validation loss: 0.3981</pre><pre>------------------------- Epoch 3 -------------------------<br>Training loss: 0.4155<br>Validation loss: 0.3852</pre><pre>------------------------- Epoch 4 -------------------------<br>Training loss: 0.4003<br>Validation loss: 0.3700</pre><pre>------------------------- Epoch 5 -------------------------<br>Training loss: 0.3842<br>Validation loss: 0.3443</pre><pre>------------------------- Epoch 6 -------------------------<br>Training loss: 0.3592<br>Validation loss: 0.3069</pre><pre>------------------------- Epoch 7 -------------------------<br>Training loss: 0.3291<br>Validation loss: 0.2652</pre><pre>------------------------- Epoch 8 -------------------------<br>Training loss: 0.2956<br>Validation loss: 0.2195</pre><pre>------------------------- Epoch 9 -------------------------<br>Training loss: 0.2684<br>Validation loss: 0.1947</pre><pre>------------------------- Epoch 10 ------------------------- Training loss: 0.2501<br>Validation loss: 0.1930</pre><h3>Results</h3><p>After training we obtain the following losses per epoch:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*2Kgu1mMuO6Y7aysJSOgAqA.png" /><figcaption>Training results: Image by author</figcaption></figure><h3>Inference</h3><p>As we can see, our model seems to have learned something. It is time to check if it has, but… how do we check it? We don’t have target tensors for data we have never seen. Here is where shifting our input target and output target tensor has an effect. As we saw before, our model learned to predict the next token when given an element. Therefore, we should be able to give our model the input tensor and the start token, and it should give us back the next element. If when the model predicts a token, we concatenate it with our previous input, we should slowly be able to add words to our output until our model predicts the &lt;EOS&gt; token.</p><p>Here is the code for that process:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/105ba72bc55dad548176d77fc32a1b97/href">https://medium.com/media/105ba72bc55dad548176d77fc32a1b97/href</a></iframe><p>The output of running this code is:</p><pre>Example 0<br>Input: [0, 0, 0, 0, 0, 0, 0, 0]<br>Continuation: [0, 0, 0, 0, 0, 0, 0, 0, 0]</pre><pre>Example 1<br>Input: [1, 1, 1, 1, 1, 1, 1, 1]<br>Continuation: [1, 1, 1, 1, 1, 1, 1, 1, 1]</pre><pre>Example 2<br>Input: [1, 0, 1, 0, 1, 0, 1, 0]<br>Continuation: [1, 0, 1, 0, 1, 0, 1, 0]</pre><pre>Example 3<br>Input: [0, 1, 0, 1, 0, 1, 0, 1]<br>Continuation: [1, 0, 1, 0, 1, 0, 1, 0]</pre><pre>Example 4<br>Input: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0]<br>Continuation: [0, 1, 0, 1, 0, 1, 0, 1, 0]</pre><pre>Example 5<br>Input: [0, 1]<br>Continuation: [0, 1, 0, 1, 0, 1, 0]</pre><p>So the model has indeed gotten the gist of our sequences, but it still makes some mistakes when trying to predict the continuation. For example, in “Example 4”, the model should predict a 1 as the first token, since the ending of the input is a 0. We can also see how during inference our sentences don’t need to have the same length, and the outputs will also not have the same length (see “Example 5”).</p><h3>Conclusion</h3><p>I believe this article can help a lot of beginner/intermediate machine learning developers learn how to work with transformer models in PyTorch, and, since the structure is the same in other languages, this tutorial is probably also useful for other frameworks like Tensorflow (hopefully).</p><p>If you have any suggestions or find any bugs feel free to leave a comment and I will fix it ASAP.</p><p><strong>Full Colab Notebook:</strong> <a href="https://colab.research.google.com/drive/15gyTrsd-OU6YZVyjwis48ysrXFPEcv9r">https://drive.google.com/file/d/15gyTrsd-OU6YZVyjwis48ysrXFPEcv9r/view?usp=sharing</a></p><p><strong>Website: </strong><a href="https://danielmelchor.com/">https://danielmelchor.com</a></p><p><strong>Contact:</strong> <a href="/service/mailto:dmh672@gmail.com">dmh672@gmail.com</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c80afbc9ffb1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/a-detailed-guide-to-pytorchs-nn-transformer-module-c80afbc9ffb1">A detailed guide to Pytorch’s nn.Transformer() module.</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>