<?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 Marcos Treviso on Medium]]></title>
        <description><![CDATA[Stories by Marcos Treviso on Medium]]></description>
        <link>https://medium.com/@mtreviso?source=rss-664d4f028ac1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9lsYFtFMwm4T9o_r4fTIXw.jpeg</url>
            <title>Stories by Marcos Treviso on Medium</title>
            <link>https://medium.com/@mtreviso?source=rss-664d4f028ac1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 16:23:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mtreviso/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[Implementing a linear-chain Conditional Random Field (CRF) in PyTorch ]]></title>
            <link>https://medium.com/data-science/implementing-a-linear-chain-conditional-random-field-crf-in-pytorch-16b0b9c4b4ea?source=rss-664d4f028ac1------2</link>
            <guid isPermaLink="false">https://medium.com/p/16b0b9c4b4ea</guid>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Marcos Treviso]]></dc:creator>
            <pubDate>Sat, 02 Mar 2019 10:01:00 GMT</pubDate>
            <atom:updated>2021-10-02T11:41:27.481Z</atom:updated>
            <content:encoded><![CDATA[<h3>Implementing a linear-chain Conditional Random Field (CRF) in PyTorch</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Usuj0XmQC_AZSuH2" /><figcaption>Random fields 😝. Photo by <a href="https://unsplash.com/@matthewmiles?utm_source=medium&amp;utm_medium=referral">Matthew Miles</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hi folks! This is my first post on Medium. I hope you enjoy it!</p><p>During the last days I’ve been implementing a CRF model from scratch using PyTorch. My idea by doing this was to understand better how a CRF model works. I’ve found a lot of online content about CRFs, including blog posts, tutorials and books. I’ve also watched the series of video lectures from Hugo Larochelle’s class on CRF models and found them very intuitive.</p><p>After watching them, I decided to implement those math equations from scratch using PyTorch (no worries about gradients whatsoever!). So, this is the purpose of this post! To share with you an easy-to-understand guide on how to implement a (<em>linear-chain</em>) CRF model!</p><p><em>Disclaimer: CRFs are a generalization of any undirected graph structure, such as sequences, trees, or graphs. In this post, I’ll focus on sequential structures, which means that our model will condition only on previous transitions. This parameterization is known as Linear Chain CRF. For the rest of this post I’ll use the acronym CRF to denominate a general CRF and its linear chain counterpart </em>interchangeably<em>.</em></p><p>In this post, I will not describe the reasons for using CRFs nor its applications. I think if you are reading this post is because you already know all that, and you are only interested in the technical part. That said, I’ll cover some the basic theory behind it and introduce the notation that will be used for writing the code.</p><p>In summary, in this post you will see:</p><ol><li>The basic theory behind CRFs;</li><li>How to find the most probable sequence of labels given a sequence of observations;</li><li>How to compute the score of a sequence of observations given their labels;</li><li>How to compute the partition function to normalize this score;</li><li>How to implement all of them in log-space (numerically stable).</li></ol><p><strong>And in the next post:</strong> how to vectorize the <em>for-loops </em>to make calculations easier for parallel computer units (GPUs say 🙌). Take a sneak peek of the vectorized code <a href="https://github.com/mtreviso/linear-chain-crf/blob/master/crf_vectorized.py">here</a>.</p><h3>The basic theory behind the scenes</h3><p>The original Conditional Random Fields paper was published at the beginning of this century <a href="https://repository.upenn.edu/cgi/viewcontent.cgi?referer=https://en.wikipedia.org/&amp;httpsredir=1&amp;article=1162&amp;context=cis_papers">[1]</a>. Since then, the machine learning community has been applying CRFs everywhere, from computational biology and computer vision to natural language processing. A quick search on google scholar with keywords like “using CRF” and “using Conditional Random Fields” returns ~20k responses.</p><p>Over the last few years, CRFs models were combined with LSTMs to get state-of-the-art results. In the NLP community, stacking a CRF layer on top of a BiLSTM was considered a rule of thumb for achieving a higher accuracy on sequence tagging problems. You can see some examples <a href="https://github.com/sebastianruder/NLP-progress/blob/master/english/part-of-speech_tagging.md">here</a> and <a href="https://github.com/sebastianruder/NLP-progress/blob/master/english/semantic_role_labeling.md">here</a>.</p><p>In a sequence classification problem, our main goal is to find the probability of a sequence of labels (<strong><em>y</em></strong>) given a sequence vectors (<strong>X</strong>) as input. This is denoted as the conditional probability <em>P</em>(<strong>y<em> </em></strong>| <strong>X</strong>).</p><p>First, let’s define some notation adapted from Larochelle’s class:</p><ul><li>Training set: input and target sequence pairs <em>{(</em><strong>X</strong><em>i, </em><strong>y</strong><em>i)}</em></li><li>The <em>i-</em>th input sequence of vectors: <strong>X</strong><em>i = [</em><strong>x</strong><em>1, …, </em><strong>x</strong>ℓ<em>]</em></li><li>The <em>i-</em>th target sequence of labels: <strong>y</strong><em>i = [y1, …, y</em>ℓ]</li><li>ℓ is the sequence length.</li></ul><p>Assuming time-wise independence, for a sample (<strong><em>X</em></strong><em>, </em><strong><em>y</em></strong>), in a regular classification problem we compute <em>P</em>(<strong>y<em> </em></strong>| <strong><em>X</em></strong>) by multiplying the probability of each item at the<em> k-t</em>h position:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*iOjOQZann91KThSChp-tZg.png" /></figure><p>Note that we are modelling <em>P(yk | </em><strong>x</strong><em>k) </em>using a normalized exponential. This is analogous to the <em>softmax</em> transformation widely used in neural networks. These are some intuitions for the reason of using the <em>exp </em>function<em>:</em></p><ol><li><strong>Underflow:</strong> when we multiply very small numbers, we get a smaller number which may suffer <em>underflow</em>.</li><li><strong>Non-negative outputs: </strong>all values are mapped between 0 and +inf.</li><li><strong>Monotonically increasing: </strong>it pushes high values up and low values down. This has a similar effect with an <em>argmax</em> operation. More <a href="https://datascience.stackexchange.com/questions/23159/in-softmax-classifier-why-use-exp-function-to-do-normalization">here</a>.</li></ol><p>We took two symbols out of the hat: <em>U and Z. </em>Let’s see what they are.</p><p><em>U</em>(<em>x, y</em>)<em> </em>is known as our <strong>emissions</strong> or <strong>unary scores</strong><em>. </em>It’s simply a score for the label <em>y</em> given our <strong>x<em> </em></strong>vector at the <em>k</em>th timestep. You can see it as the <em>k</em>th output of a BiLSTM. Actually, in theory, our <strong>x </strong>vector can be anything you want. In practice, our <strong>x</strong> vector is usually the concatenation of surrounding elements, like word embeddings from a sliding window. Each <em>unary</em> factor is weighted by a learnable weight in our model. This is easy to understand if we consider them as LSTM outputs.</p><p><em>Z</em>(<em>x</em>)<em> </em>is commonly referred as the <strong>partition function</strong>. We can think of it as a normalization factor since we’d like to get probabilities in the end. This is analogous to the denominator of the<em> softmax </em>function.</p><p>So far, we described a regular classification model with a “final softmax activation” in order to get probabilities. Now we are going to add new learnable weights to model the chance of a label <em>yk</em> being followed by <em>yk+1. </em>By modelling this, we are creating a dependency between successive labels. Thus, the name <em>linear-chain CRF! </em>In order to do so, we multiply our previous probability by <em>P(yk+1 | yk), </em>for which we can use exponential properties to rewrite it as unary scores <em>U</em>(<strong><em>x</em></strong><em>, y</em>) plus learnable <strong>transition scores </strong><em>T</em>(<em>y, y</em>)<em>:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*aoIcDIgR2I_azRgyq5u8AA.png" /></figure><p>In code, <em>T</em>(<em>y, y</em>)<em> </em>can be seen as a matrix with shape <em>(nb_labels</em>, <em>nb_labels), </em>where each entry is a learnable parameter representing the transition of going from the <em>i-th</em> label to the <em>j-th</em> label. Let’s review all our new variables:</p><ul><li><strong>emissions or unary scores </strong><em>(U): </em>scores representing how likely is <em>yk </em>given the input <strong>x</strong><em>k.</em></li><li><strong>transition scores </strong><em>(T): </em>scores representing how likely is <em>yk</em> followed by <em>yk+1</em></li><li><strong><em>partition function</em></strong><em> (Z): </em>normalization factor in order to get a probability distribution over sequences.</li></ul><p>The only thing left to be properly defined is the partition function <em>Z:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*bdWqw7jqM5cys132cF0DhQ.png" /></figure><p>Turns out it’s not trivial to compute <em>Z</em>(X) because we have too many nested loops 😖. It’s a sum over all possible combinations over the label set at each timestep<em>.</em> To be more precise, we have ℓ computations over the label set. This give us a time complexity of <em>O(|y|^</em>ℓ<em>).</em></p><p>Luckily, we can exploit the recurrent dependencies and use dynamic programming to compute it efficiently! The algorithm that does this is called <strong>forward algorithm </strong>or <strong>backward algorithm — </strong>depending on the order that you iterate over the sequence. Not to be confused with forward and backward propagation used in neural networks.</p><p>And that’s all we need to know to start our implementation journey! If you got lost during my explanation, there are very good resources out there explaining CRFs in more detail. Like <a href="http://blog.echen.me/2012/01/03/introduction-to-conditional-random-fields/">this excellent tutorial</a> by Edwin Chen, or <a href="https://homepages.inf.ed.ac.uk/csutton/publications/crftutv2.pdf">this extensive tutorial</a> by Sutton and McCallum, or <a href="http://www.cs.columbia.edu/~mcollins/crf.pdf">this right-to-the-point notes</a> by Michael Collins.</p><h3>Code</h3><p>Let’s start our code by creating a class called CRF that inherits from PyTorch’s <em>nn.Module</em> in order to keep track of our gradients automatically. Also, I added special tokens for the beginning/end of the sentence, and a special flag to inform whether we are passing tensors with batch-first dimension or not.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae855a1b37b08fd84412c20cd831172c/href">https://medium.com/media/ae855a1b37b08fd84412c20cd831172c/href</a></iframe><p>We could add a special token for a pad id as well. If we do this, we have to make sure to enforce constraints to prevent transitions <em>from</em> padding and transitions <em>to</em> padding — except if we already are in a pad position. We can see that our transitions scores <em>T</em> are denoted as the matrix <em>self.transitions </em>and encoded using <em>torch.parameter. </em>In this way,<em> </em>PyTorch will learn these weights with autodiff! Great!</p><h3>Defining the loss function</h3><p>In a supervised classification problem, our goal is to minimize the expected error during training. We can do this by defining a loss function <em>L</em> which takes as input our predictions and our true labels and returns a zero score if they are equal or a positive score if they are different — indicating an error.</p><p>Note that we are calculating <em>P</em>(<strong>y<em> </em></strong>| <strong><em>X</em></strong>) and this is something we want to maximize. In order to frame this as a minimization problem, we take the negative log of this probability. This is also known as the <em>negative log-likelihood loss (NLL-Loss). </em>In our case, we get: <em>L = </em>-<em> log</em>(<em>P</em>(<strong>y<em> </em></strong>| <strong><em>X</em></strong>)). And applying log-properties, like <em>log(a</em>/<em>b) = log(a) - log(b)</em>, we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*-bHSBjJWkodxb3YK1XULjQ.png" /></figure><p>Where <em>Z_log</em> means we take the <em>log</em> during the computation of the partition function. This is going to make things easier for us later when we apply the forward-algorithm. So, let’s check how the code looks for this part:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/559dc5b2be858658061a346f0d2176d5/href">https://medium.com/media/559dc5b2be858658061a346f0d2176d5/href</a></iframe><p>Our <em>forward</em> pass is simply the <em>NLL loss </em>(not to be confused with the forward-algorithm for computing Z(X)), in which we inserted the minus symbol in front of the regular <em>log_likelihood</em> method. The <em>log_likelihood </em>is computed by first computing the scores and the log partition methods, and lately subtracting each other. Furthermore, we pass a mask matrix to those methods so they can ignore computations associated with pad symbols. For completeness, the mask matrix looks like this:</p><pre>input = [[&#39;lorem&#39;, &#39;ipsum &#39;dolor&#39;, &#39;sit&#39;, &#39;amet&#39;],<br>         [&#39;another&#39;, &#39;sentence&#39;, &#39;here&#39;, &#39;&lt;pad&gt;&#39;, &#39;&lt;pad&gt;&#39;]]</pre><pre>mask = [[1, 1, 1, 1, 1],<br>        [1, 1, 1, 0, 0]]</pre><h3>Computing the numerator: scores</h3><p>Since we applied <em>log</em> to the <em>exp </em>function, the numerator is just the summation of our emission and transition scores at each timestep. In code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a2cff15e01646b3b4d68657bf1a4f4b/href">https://medium.com/media/9a2cff15e01646b3b4d68657bf1a4f4b/href</a></iframe><p>In order to understand this code, you have to think that all operations are the same for each sentence in the batch. So, we start by taking the tags for the first word in each batch by calling tags[:, 0]. Similarly, we sum the mask over the timestep dimension to get a list of lengths, which would be [5, 3] for the previous example. In practice, it’s returned a <em>torch.LongTensor</em> with shape (batch_size,). For instance, let’s look at the line 28:</p><pre>emissions[:, 0].gather(1, first_tags.unsqueeze(1)).squeeze(1)</pre><ol><li>First, we select all batches from the first timestep: emissions[:, 0], which returns a tensor with shape (batch_size, nb_labels).</li><li>Then we want to select only the values from the columns (<em>dim=1</em>) that are in the <em>LongTensor</em> first_tags, which has shape (batch_size,). Since emissions is a 2D matrix, we <em>unsqueeze </em>the last dimension of first_tags to get the shape (batch_size, 1): first_tags.unsqueeze(1)</li><li>Now that they have the same shape, we can use the <em>gather </em>function to select the values inside first_tags in the specified dimension of emissions: emissions[:, 0].gather(1, first_tags.unsqueeze(1))</li><li>Finally, this will result in a matrix with shape (batch_size, 1), so we <em>squeeze</em> it back to get a 1D <em>LongTensor.</em></li></ol><p>This simple procedure is used throughout the code to select a group of labels within a specified dimension.</p><p>The last thing I want to talk about this code is how we ignore scores associated with a padding symbol. And the idea to solve this is very simple: we perform an element-wise multiplication between the two vectors (score and mask vectors), to zero-out the scores in timesteps associated with a pad position.</p><h3>Computing the partition function: forward algorithm</h3><p>Now that we have computed our scores, let’s focus on our denominator. In order to compute the partition function efficiently, we use the forward algorithm. I will describe it briefly and show how we can compute it in log-space.</p><p>The pseudo-code for the forward-algorithm goes as follows:</p><p>1) Initialize, for all values of <em>y’2:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*Qx0RtpS3ceeG3dnpWmB6hw.png" /></figure><p>2) For <em>k=2 to </em>ℓ-1, for all values of <em>y’k+1 </em>(log-space)<em>:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*CIVs1m9WKvkqUxbveIJ33A.png" /></figure><p>3) Finally:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*5HI7ez_c1S_4t5zqMutZXg.png" /></figure><p>Observe that in the 2nd step we take a log of a summation of exps. This can be problematic: if a score for a given label <em>y’k </em>is too large, then the exponential will grow very fast to a <strong>very </strong>large number. So, before we take the log in the end we might find an <em>overflow</em>. Luckily, there is a trick for making this operation stable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*2hLkdRgbBnK4NybUNhuY3g.png" /></figure><p>The proof that the left side is equal to the right side looks like this:</p><pre>_ = log sum(exp(zk))<br>  = log sum(exp(zk-c) * exp(c))<br>  = log exp(c) + log sum(exp(zk-c))<br>  = c + log sum(exp(zk-c))</pre><p>Set <em>c</em> as <em>max</em>(<em>z</em>) and we are done. In addition, PyTorch already have this stable implementation available for us in torch.logsumexp. Let’s now code the algorithm above using PyTorch:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b636f0c0657e3f522a08fbd4876f79bd/href">https://medium.com/media/b636f0c0657e3f522a08fbd4876f79bd/href</a></iframe><p>The code above is very similar to the way we have computed the scores in the numerator. In fact, we are computing scores! But now we are accumulating them by looking at previous iterations. I added comments about shapes so you can understand what’s going on.</p><p>There is just one thing here that we didn’t see before (<em>kind of</em>):</p><ul><li>alphas = is_valid * new_alphas + (1 — is_valid) * alphas: In this line, we are changing the current values of alpha by new ones if we didn’t reach a pad position, and keeping the same values otherwise. To see how this works, take a look at this example when we are at the timestep <em>i=1</em>:</li></ul><pre>&gt;&gt;&gt; mask<br>tensor([[1., 0., 0.],<br>        [1., 1., 0.],<br>        [1., 1., 1.]])<br><br>&gt;&gt;&gt; alphas<br>tensor([[-0.7389, -0.6433, -0.0571, -0.3587, -2.1117],<br>        [ 1.0372,  1.8366, -0.9350, -1.2656, -0.5815],<br>        [ 0.1011,  0.7373,  0.0929, -0.8695,  0.7016]])</pre><pre>&gt;&gt;&gt; new_alphas<br>tensor([[11.1889, 10.6471, 11.0028, 11.0248, 11.0909],<br>        [10.3975, 11.0104,  8.5674, 10.2359, 13.9150],<br>        [10.1440,  9.9298, 11.3141, 10.1534, 10.3397]])</pre><pre>&gt;&gt;&gt; is_valid = mask[:, 1].unsqueeze(-1)<br>&gt;&gt;&gt; is_valid<br>tensor([[0.],<br>        [1.],<br>        [1.]])</pre><pre>&gt;&gt;&gt; is_valid * new_alphas + (1 — is_valid) * alphas<br>tensor([[-0.7389, -0.6433, -0.0571, -0.3587, -2.1117],<br>        [10.3975, 11.0104,  8.5674, 10.2359, 13.9150],<br>        [10.1440,  9.9298, 11.3141, 10.1534, 10.3397]])</pre><p>We have updated the 2nd and 3rd sequences but not the 1st because at timestep <em>i=1 </em>we reached a pad position.</p><p>As a good observation, you can see that once we take the <em>logsumexp</em> we are already in log-space! So, we can just add the values of alpha to our scores. And finally, we take one more <em>logsumexp </em>operation at the final timestep to return the final values of reaching the end of the sentence — so we are still in log-space.</p><p>The time complexity of this algorithm is O(𝓁|<em>y</em>|²), which is much lower than the exponential bound we had with the naive approach.</p><h3>Finding the <em>best</em> sequence of labels</h3><p>Now that we computed the partition function, we have almost everything done. If we compute the backward algorithm as well — which is just traversing the sequence backwards — we could find the label that maximizes <em>P</em>(<strong>y</strong><em>k</em> | <strong>X</strong>) at each timestep <em>k. </em>Interestingly, this<em> </em>would be the optimal solution if we assume the CRF is the true distribution. And it can be formulated like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*YCaPGVK5nomxlDhGizo6UA.png" /></figure><p>Where the <em>α</em> scores come from the forward algorithm and the <em>β </em>scores come from the backward algorithm. In order to find the best sequence of label <strong>y</strong>* we could take the <em>argmax</em> at each timestep:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*F0EVqqAOaz6oMsVAGE2xlQ.png" /></figure><h4>Viterbi algorithm</h4><p>But, turns out we don’t need to compute the backward algorithm in order to find the most probable sequence of labels. Instead we can simply keep track of the maximum scores at each timestep during the forward algorithm. And once we are done, we can follow the backward trace of the max operations (<em>argmax</em>) in order to <strong>decode</strong> the sequence that maximizes the scores. This is exactly what the code below does:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19fe573c2965a1b3a36d6914245558f9/href">https://medium.com/media/19fe573c2965a1b3a36d6914245558f9/href</a></iframe><p>This algorithm is known as Viterbi algorithm. It is almost the same as the forward-algorithm we have used in the log_partition function, but instead of having regular scores for the whole sequence, we have maximum scores and the tags which maximize these scores<em>. </em>In other words, we have replaced the <em>torch.logsumexp </em>operation by <em>torch.max</em>, which returns the <em>max</em> and the <em>argmax </em>together.</p><p>So, everything we need to do now is to pick these final tags and follow the backward trace to find the whole sequence of “<em>argmax”</em> tags. The continuation of the above code goes as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef5c713855b09a749779ce2e513aeffd/href">https://medium.com/media/ef5c713855b09a749779ce2e513aeffd/href</a></iframe><p>See that for each sample we are iterating over the backtrace of that sample, and in each timestep we are inserting the tag which maximizes the scores at the beginning of best_path. So, at the end, we have a list where the first element corresponds to the first tag and the last element corresponds to the last tag valid tag (<em>see line 15</em>) of the sequence. Note also that .insert(0,) in python is O(n), so a faster approach would be to use .append() and then reverse the list later.</p><p>That is it! When we compute the <em>find_best_path</em> operation for all samples in the batch we are done!</p><h3>Putting all together</h3><p>The full code is available here: <a href="https://github.com/mtreviso/linear-chain-crf">https://github.com/mtreviso/linear-chain-crf</a>. Take a look at main.py and bilstm_crf.pyto see the CRF in practice!</p><h3>Conclusion</h3><p>Well, this post got longer then I intended 😛. Feel free to make this code more efficient and leave a comment to show us how you managed to do it 🙂.</p><p>Finally, I think it is worth to mention that If you’d like to use a CRF model in production, I strongly suggest you to use a well-tested and efficient implementation, like <a href="https://github.com/kmkurn/pytorch-crf">this great pytorch package</a>, or the one provided by the <a href="https://github.com/allenai/allennlp">allennlp library</a>.</p><p>In the next post we’ll see how we can vectorize our <em>for-loops</em> to calculate the partition function and the Viterbi algorithm.</p><h3>More info</h3><p>CRFs are only one among many sequential models available. I highly recommend you to take a look at <a href="http://lxmls.it.pt/2016/sequencemodels.smith.7-23-16.pdf">this Noah Smith presentation on sequential models</a> or at <a href="https://andre-martins.github.io/docs/dsl2018/lecture_05.pdf">this lecture by André Martins</a> to see some visual examples of the algorithms presented in this post. Or even better, you can attend the next <a href="http://lxmls.it.pt/2019/">Lisbon Machine Learning Summer School</a>, which will cover sequential models and many more interesting topics about Machine Learning and Natural Language Processing!</p><h3>References</h3><ul><li>Hugo Larochelle’s lectures on CRFs: <a href="http://www.dmi.usherb.ca/~larocheh/neural_networks/content.html">http://www.dmi.usherb.ca/~larocheh/neural_networks/content.html</a></li><li>Pytorch tutorial — Advanced: Making Dynamic Decisions and the Bi-LSTM CRF: <a href="https://pytorch.org/tutorials/beginner/nlp/advanced_tutorial.html">https://pytorch.org/tutorials/beginner/nlp/advanced_tutorial.html</a></li><li>Michael Collins’s notes on Log-Linear Models, MEMMs, and CRFs: <a href="http://www.cs.columbia.edu/%7Emcollins/crf.pdf">http://www.cs.columbia.edu/%7Emcollins/crf.pdf</a></li><li>Michael Collins’s notes on the Forward-Backward Algorithm: <a href="http://www.cs.columbia.edu/~mcollins/fb.pdf">http://www.cs.columbia.edu/~mcollins/fb.pdf</a></li><li>Tutorial by Sutton and McCallum — An Introduction to Conditional Random Fields: <a href="https://homepages.inf.ed.ac.uk/csutton/publications/crftutv2.pdf">https://homepages.inf.ed.ac.uk/csutton/publications/crftutv2.pdf</a></li><li>Edwin Chen blog post: <a href="http://blog.echen.me/2012/01/03/introduction-to-conditional-random-fields/">http://blog.echen.me/2012/01/03/introduction-to-conditional-random-fields/</a></li><li>An Overview of Conditional Random Fields by Ravish Chawla: <a href="https://medium.com/ml2vec/overview-of-conditional-random-fields-68a2a20fa541">https://medium.com/ml2vec/overview-of-conditional-random-fields-68a2a20fa541</a></li></ul><p>🔍 <em>Special thanks to @flassantos31, @erickrfonseca and @thales.bertaglia for reviewing this post.</em></p><p>🔮 Post-review thanks: <a href="https://medium.com/u/a800706492c5">André Luís Macêdo Farias</a> for pointing the correct time complexity for computing <em>Z </em>using the naive approach.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16b0b9c4b4ea" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/implementing-a-linear-chain-conditional-random-field-crf-in-pytorch-16b0b9c4b4ea">Implementing a linear-chain Conditional Random Field (CRF) in PyTorch 🔥🛠</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>