<?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 Yash on Medium]]></title>
        <description><![CDATA[Stories by Yash on Medium]]></description>
        <link>https://medium.com/@daga.yash?source=rss-ed1ff4a9d6bd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*O5h8eljPdhsV793zVOa9fQ.jpeg</url>
            <title>Stories by Yash on Medium</title>
            <link>https://medium.com/@daga.yash?source=rss-ed1ff4a9d6bd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 18:50:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@daga.yash/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[The Ground Up series(Part 6): Exact Inference Where Graphs Learn To Talk]]></title>
            <link>https://medium.com/@daga.yash/the-ground-up-series-part-6-exact-inference-where-graphs-learn-to-talk-574954c23a74?source=rss-ed1ff4a9d6bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/574954c23a74</guid>
            <category><![CDATA[probabilistic-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Yash]]></dc:creator>
            <pubDate>Tue, 23 Dec 2025 18:40:37 GMT</pubDate>
            <atom:updated>2025-12-23T18:40:37.954Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rEHDxg-_EWgg1cj1K-ES4Q.png" /><figcaption><strong>Nodes whispering on the gossips :P</strong></figcaption></figure><p>Voila detectives! Over the last 5 parts of this series, we’ve built a huge and an elaborate evidence board for tracking our elusive thief who happens to run away at a crucial time. We’ve mapped hidden notes in his documents to extract something meaningful (LDA), tried tracking him through his sequence through the sequence of his movement patterns (HMMs), understood the cause-and-effect relationship in his documents (DAGs), seen the mutual dependencies between the cities, food, and travel (UGMs), and tried unifying everything under the hood of Factor Graphs.</p><p>But here’s the thing! We know <em>how </em>the variables are connected, we ‘ve made certain assumptions by the way the thief moves and leaves behind cues, and we’ve come up with our own Probabilistic Graphical Model. That is only half the job done fellow detectives.</p><p>When a new evidence arrives — say a credit card transaction in Tokyo, a postcard in a Mumbai local, how do we update our beliefs? How do we answer queries like “Given everything we’ve observed, where is he most likely to steal next?”</p><p>This is where our rubber meets the road. This is what we can informally call inference. It’s time to turn our graphical structures into problem-solving machines :)</p><blockquote><em>As Kevin P. Murphy puts it in his book “Probabilistic Machine Learning: Advanced Topics”:</em><br>“In the probabilistic approach to machine learning, all unknown quantities — be they predictions about the future, hidden states of a system, or parameters of a model — are treated as random variables, and endowed with probability distributions. The process of inference corresponds to computing the posterior distribution over these quantities, conditioning on whatever data is available.” <em>(Section 7.1)</em></blockquote><p>Let us see what this means mathematically and how we can actually compute these posteriors.</p><h3>The Heart of Inference: What Are We Actually Computing?</h3><p>Let h represent the unknown variables, and D represent the known variables. Given a likelihood p(D|h) and a prior p(h), we can compute the posterior p(h|D) using Bayes’ rule:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*I-evKshu6FY7p5eUpTVpuA.png" /></figure><p>The main computational bottleneck is the normalizing constant in the denominator which is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/237/1*LrieaoNMkZMldwvq7eOpYw.png" /></figure><p>(For discrete variables, it would be a summation over the various cases.) This integral is needed to convert the unnormalized joint probability p(h,D) into a normalized posterior p(h|D).</p><p>Similarly, computing the posterior marginals requires:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*55vaKj_I4RodDMoArupdYg.png" /></figure><p>To realize, Integration is at the heart of Bayesian inference, whereas differentiation is at the heart of optimization.</p><h3>Common Inference Patterns</h3><p>Before diving into algorithms, Murphy discusses three main patterns of inference that arise in practice. Understanding these helps us choose the right approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vzgWfxrLGkUVtxopzVqXaw.png" /><figcaption><strong>Img source: Kevin P. Murphy, page no. 376</strong></figcaption></figure><h4>Pattern 1: Global Latent Variables</h4><p>This arises when we need to do inference in models with global hidden variables like parameters θ shared across all N observed training cases. Refer to part a of the figure above. The joint distribution in this case has the form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*-_zjCl8058DqcWRb5pahxQ.png" /></figure><p>Our goal is to compute the posterior</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/134/1*TyuPeVnGaffdLEsMtHvr6g.png" /></figure><p>This is the usual setting for a Bayesian Supervised Learning.</p><h4>Pattern 2: Local Latent Variables</h4><p>This arises when we need to perform inference in models which have local latent variables like hidden states z_{1:N}; we assume the model parameters θ are <em>known</em>. Refer to part b of the figure above. Joint probability distribution in this case becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*y1aWnqr0RUHtU7ZKxtlmjg.png" /></figure><p>The goal is to compute the posterior</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/100/1*OV0kh0UqHnMQeB-njjla1w.png" /></figure><p>for each n. This is the setting for most Probabilistic Graphical Model inference method and this is what precisely we are interested in.</p><h4>Pattern 3: Global and Local Latent</h4><p>The third pattern arises when we are interested in performing inferencing in models with both global and latent variables. Refer to the part c of the figure above. The corresponding joint pdf then becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*rKNZhwBO2y7SpyHwiHODDA.png" /></figure><p>Here we model uncertainty in both the local variables z_n and the shared global variables θ. This is a relatively uncommon setting in the ML community because uncertainty in parameters θ is negligible compared to the uncertainty in the local variabes z_n. The parameters come informed from all N examples, whereas each local latent z_n comes only from one single sample datapoint, x_n. We are not much interested in this case.</p><h3>Exact vs Approximate Inference</h3><p>In some cases, we can perform example posterior inference in a tractable manner. In particular, if the prior and the likelihood are <em>conjugates </em>of each other, the posterior will be analytically tractable.</p><p>Like for example, if both prior and likelihood come from the exponential family. (Think about how the posterior just becomes another member of the exponential family because of this)</p><p>The second case when we can compute posterior as it is, is when the D unknown variables are all discrete, say each with K states. In this case too we see that the denominator becomes a sum of K^D terms and often it becomes too large to be tractable. But if the distribution does encompass a PGM then we can write the joint in terms of products of local terms.</p><p>This is where Variable Elimination and Message Passing will come in.</p><p>So then, in cases where exact inferencing is not possible, approximate inferencing comes to our rescue.</p><p>And what would the approaches be? In Layman terms, we can use a sampling based approach to construct our target distribution rather than calculate it directly. For this, we could substitute the true distribution with another distribution that resembles the original one (the posterior that we are interested in) but easier to sample from.</p><p>Okay, this is a lot to digest at once, right? Don’t worry, we shall discuss the Approximate Inferencing techniques in the next one! For now, let us look at Exact Inferencing.</p><h3>Discrete Marginalization: The foundation</h3><p>Let’s start with the simplest case to build intuition. Consider a chain graph of four binary variables something like this —</p><p>A → B → C → D</p><p>The factorization in this case is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*st-UWnDdJ2RF7rzPtfJ_zg.png" /></figure><p>Our goal is to compute the marginal say, p(B).</p><p>The brute force approach would be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*6A5OSwd9lHcq41RYaZ0LhA.png" /></figure><p>This requires summing up 2³ = 8 values, with 3 multiplications each time, and thus a total of 8*3+7 = 31 operations.</p><p>But hang on, note that D is present only in one factor p(D|C), and since</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/146/1*Y5D6OsvaW3DBsDed1d_v5w.png" /></figure><p>therefore we can eliminate D without residue! Next up,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/174/1*AITbB6CVl36U5mktjtjCNQ.png" /><figcaption><strong>just 2 summations (C takes zero or 1)</strong></figcaption></figure><p>where subscript tells that we eliminate C and express the marginal in terms of B, and C already contained the marginal of D(which turned out to be 1, but it did contain it right, so the eliminated variables are C,D at this point). Again, from the side of A if we eliminate A and express B as a marginal of A, we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/206/1*gJ2vLEDJcGvKGSmh7QFs1A.png" /><figcaption><strong>4 multiplications, 2 summations over A (can take 0 or 1)</strong></figcaption></figure><p>and finally, we have</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/142/1*1PjmaLWHzVfmvorusFLt7w.png" /><figcaption><strong>2 multiplications</strong></figcaption></figure><p>Thus, we see the power of the distributive law! By pushing sums inside products, we’ve dramatically reduced the computations.</p><h3>The Variable Elimination Algorithm</h3><p>The Variable Elimination (VE) algorithm just formalizes this insight. Let us see this using an example to understand.</p><p><strong>Input</strong>: The graphical model and its associated factorization, the target variable set (whose marginal/joint is required)</p><p><strong>Algorithm</strong>:</p><ol><li>Specify an order first to eliminate the remaining variables.</li><li>Set ϕ as the list of factors.</li><li>For each elimination variable in order:</li></ol><ul><li>Select all factors ϕ′ from ϕ that involve the current elimination variable</li><li>Multiply them and sum over all possible values of the elimination variable</li><li>Result: a function μ(residual) of the other variables covered by the factors in ϕ′</li><li>Remove the factors ϕ′ from ϕ and insert μ into ϕ</li></ul><p>4. Multiply the remaining factors in ϕ to get the desired distribution.</p><p>Consider the following network with all variables taking binary values —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*qpcRG_CMNhcVBzT5IgMFuQ.png" /></figure><p>Now suppose we want to compute p(J=1) (well who doesn’t like having a job xD) the marginal probability of the person getting a job. Since we have 8 binary variables, we could simply enumerate over them all possible assignments for all the variables (except for J), adding up the probability of each joint:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*i4XSmT143Uwr97n9zLU8IQ.png" /></figure><p>But this would take O(2⁷) time. Imagine how much time it would take for more number of variables let alone each of them taking real values.</p><p>But we can be smarter by pushing sums inside products. This is the key idea behind the VE algorithm.</p><p>Let us see for this particular example how we utilize the VE algorithm.</p><p>The joint factorizes as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*zqMBaS3dYlaLFUjHYV3ggA.png" /></figure><p>(Remember how we did with Markov models)</p><p>We decide for an elimination order C,D,I,H,G,S,L ( which means starting with C we start eliminating variables by marginalizing over the variables in the said order), and we redistribute the summations in this order:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9hhcHdPHPBQGlUOMEAgD1w.png" /></figure><p>Step-by-step elimination:</p><ol><li>Eliminate C:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*JwAa8Y1gMWqmO1tww-u2ng.png" /></figure><p>2. Eliminate D:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*Np6l9NcCmjf2u26b8Wvwxg.png" /></figure><p>3. Eliminate I:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*SgVOnG5IX_96cD2ga_CqSA.png" /></figure><p>4. Eliminate H:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*qIZqZqmYpm_eQVShElto6A.png" /></figure><p>5. Eliminate G:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*FHqHQSFHy2FoYZbKP-BB6g.png" /></figure><p>6. Eliminate S:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*5o-sdSgNMsR1hejQSjwdFw.png" /></figure><p>7. Eliminate L:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*71sjKftjbxZfCD8q05q8FA.png" /></figure><p>Thus, we see how using simple marginalization we were able to reduce so many steps that would have otherwise taken much more computation.</p><p>We can utilize the above technique to compute any marginal of interest, say p(J) or p(J,H). To compute a conditional, we will simply need to take a ratio of the two marginals, where the visible variables have been “<em>clamped</em>” to their known values (hence, no need of summing over them). For example,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*9I4gNmabIU8cY60SrBjmUw.png" /></figure><h4>Elimination Order and Residual Graphs</h4><p>You must have wondered whether the computational cost taken in order to get to the marginal over J is dependent on the elimination order that we chose.</p><p>Well to answer, Yes! Elimination order dramatically affects computational cost.</p><p>The number of computations in each elimination step depends on the number variables covered by the participating factors. This would relate to the clique size of the residual graph.</p><p>Elimination Graph Process:</p><ul><li>Start with the undirected representation of the original graphical model</li><li>To eliminate each variable, remove the corresponding node and its attached edges</li><li>But <strong>add fill-in edges</strong> between the remaining variables of the residual factor (if not already present)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*wpyyQGuUFEEyGn8Ci4DkDg.png" /><figcaption><strong>Edge creation when nodes are marginalized-order C,D,I.</strong></figcaption></figure><p>In our example of the elimination process in the order C, D, I, H, G, S, L; firstly when we eliminate C, we already have the edge between C and D.</p><p>Then when we eliminate D, we see that the nodes I and G (to which D was connected to) are already connected.</p><p>Finally, when we eliminate node I, then see we have a new edge between G and S, because I was connected to them, and that is how we got the residual factor τ3​(G,S). In similar way, the elimination proceeds.</p><p>For example, if the Elimination order was — G, I, S, L, H, C, D. Notice, when we eliminate G from the joint distribution then the corresponding residual would be a function of the terms it was connected to, in short the residual would be a function of I, D, L, J, H (5 variables — much more computationally expensive!)</p><h4>Computational Complexity of VE</h4><blockquote><em>In his book ‘Probabilistic Approach to Machine Learning Advanced’, Kevin P. Murphy states, </em>“The running time of VE is clearly exponential in the size of the largest factor, since we have to sum over all of the corresponding variables.”</blockquote><p>Let</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/30/1*F1H-ZcmaI-Uq4IWHl9TcgA.png" /></figure><p>be the (undirected) graph induced by applying VE to G, using elimination order &lt;. The temporal factors thus generated by VE correspond to maximal cliques in the graph</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/30/1*F1H-ZcmaI-Uq4IWHl9TcgA.png" /></figure><p>For example, given our original Elimination Ordering (C, D, I, H, G, S, L), the maximal cliques are as follows —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*vt1VrCiLW7STmZfya9l54Q.png" /></figure><p>It thus becomes clear to us that the time complexity of VE is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/131/1*GFTIF6XUUbcyf6radLF9iA.png" /></figure><p>where we can say that C(G) are the maximal cliques in graph G, |c| is the size of clique c, and here we assume that each of our random variables takes K states each,</p><p>We define w_{&lt;} as the induced width of a graph given an elimination ordering &lt; which is the size of the largest clique in the induced graph (i.e., after an elimination the graph that forms)-1. So, the complexity of VE with ordering &lt; is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/128/1*EnBO4eB8l7zgKcFWXrjHaQ.png" /></figure><p>One question that you might be curious about is that is there any way of finding the optimal elimination order? Unfortunately, this problem is NP-complete problem.</p><p>But how do we then pick a good elimination order?</p><p>Don’t worry, we shall try seeing that in this next sub-topic.</p><h4>Picking a good elimination order</h4><p>Since choosing an elimination ordering with minimal width is NP-complete, it is common to use some greedy approximations like the min-fill heuristic. But how does that work?</p><p>We eliminate any node which would NOT result in formation of new edges. For example, if we try eliminating G in our given example at an early step then see how many nodes it is already connected to in the first step? It is connected to D, I, L, and H, which means the residual factor would contain all these 4 terms and we would have so many extra connections between say D and H, D and L as a result of that! We would actually have a clique of size 4 = Massive computations, right?</p><p>Compare it to the case if we eliminate C at the start, the residual factor would just contain D and no extra connections would be made in the residual graphical model.</p><p>Another heuristic could be like this —</p><p>We assign different nodes different weights, and we try to minimize the weight of the created cliques at each step. This is called the Min-Weight Heuristic.</p><h4>Drawbacks of VE</h4><p>By now you would have realised that if we had to compute say all the marginals, we would have to run VE from scratch from the first step for each query variable. That is WASTEFUL! Just think how many intermediate computations are we repeating here.</p><p>Suppose, we want to also find the marginal of p(H=1) in our example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*qpcRG_CMNhcVBzT5IgMFuQ.png" /></figure><p>And suppose we choose our elimination ordering as (C, D, I, S, L, H, G). We would realise that we are repeating so many computations that we already had done while computing the marginal p(J=1), like for example eliminating C, D, I etc.</p><p>Here we plant the idea of a variable sending a ‘message’ to its neighbors.</p><p>This message would encode its own information and the information it had received from other nodes. (We had already seen this in HMMs but we shall do this practice once again.)</p><p>Let us see it in the next section for more clarity.</p><h3><strong>Message Passing (Chinese whispers, eh?)</strong></h3><p>Each elimination variable sends a message to its neighbors. The message would encode its own information and the information it had received earlier from the other nodes.</p><p>Consider the chain —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*tWCfUUM2Or9mKjjes0Rtqg.png" /></figure><p>Suppose we want to compute the marginal p(Xn).</p><p>Message from the left:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*E0wpAKC2N0LWuFvrZPrAtA.png" /><figcaption><strong>Message propagating from node 1 to node 2</strong></figcaption></figure><p>(Subscript 2 denotes the residual, and the superscript 1 denotes the variable eliminated.)</p><p>This message then propagates to the right as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*RcxCAIlH1Oe70HY6iSNtaw.png" /><figcaption><strong>Message propagating from node 2 to node 3</strong></figcaption></figure><p>(See how it incorporates the information packed from X_1 and combines it with the information it has and passes it to 3.)</p><p>This message till it reaches the target node n:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*EMPreyDWyqak9haJy9B4oQ.png" /></figure><p>Similarly messages from the right propagate as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*8KaHnQpaQwzX-arN_suNYA.png" /></figure><p>Consider the above means, we are packing all information stored in variable N and sending it to variable N-1.</p><p>This message propagates to the left as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*rdQ2U3n7lwSA3ZzcqY938w.png" /></figure><p>Now the variable N-1 contains self information and the information that N had sent over to N-1, and this in turn it packs over and sends it to the variable N-2, and so on till it reaches the target node n as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*hZVGgRcWO0MWlM76IojkzA.png" /></figure><p>So finally,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*vhz2KDpwYxMNBgoA7VWC4A.png" /></figure><p>But how is this different to VE?</p><p>Notice if we have to compute the marginal say p(X5) or p(X8, X10). We can utilize so many of these products because we are calculating them independently.</p><p>The pendant vertices should initiate process, and then we can calculate in a parallel fashion — the forward passing and the backward passing.</p><p>Each vertex u with k neighbors have to wait to receive messages from (k-1) of them. Then it combines those and sends to the remaining neighbor v.</p><p>And say, if it has received the messages in the backward message passing, then it sends over to the next neighbor. So as soon as a variable receives all the information in a particular direction from the variables, it packs them with itself and conveys it on irrespective of the direction. And when it receives the information in the opposite direction, then it multiplies with the other residual to give the marginal, and simultaneously passes the information forward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*RvEMZgleXoCudbVQ3faukA.png" /><figcaption>To note: All messages have not been shown here!</figcaption></figure><p>For example, in the above structure, suppose X3 receives information from X5 and X6 first before it receives information from X2 (which in turn needs information sent from X1 and X4). In that case, it will pack its own information and send it first to X2, and when it receives information from X2 it packs its own information and sends over the message to X5 and X6.</p><p>Important to note that the Message passing algorithm works on trees, it does not work on graphs with cycles. It can work both with directed and undirected graphical models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*BrxdNBmQ_fJ2bHQ1T7uujA.png" /></figure><p>Look at the conflict in messages in case when we have our graph containing cycles. X2 sends a message directly to X5 (denoted by the purple arrow) and at the same time, it conveys message through X3 to X5. These messages encode different information, and when they do meet at X5, which one is “right”? The same happens in the reverse direction. That is why message passing on cycles can give incorrect answers/</p><h3>Message Passing in Factor Graphs</h3><p>In our last article we discussed about factor graphs. Let us take a look at how message passing is done in this case.</p><p>Consider the following factor graph —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*xJ_MmTfnTrMLl7UWemae_Q.png" /></figure><p>The joint distribution in this case would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*H5PntLb0msY_SKHrLg2e_g.png" /></figure><p><strong>Message Passing rules for factor graphs:</strong></p><ol><li>From variable x to factor f.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*nioRkZeUmNszGutthdcwBA.png" /></figure><p>2. From factor f to variable x:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*oTy-JYxoZOCna28uypRc4A.png" /></figure><p>Variable nodes multiply the incoming messages, and factor nodes multiply by the factor and marginalize out other variables.</p><p>Let us see for a sample factor graph —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*Ct4v4xysVCsEXSQkrUe4Gg.png" /></figure><p>Notice the flow of messages. But what would the messages look like? Let us see.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*C6eQCc75MTJjvg7EhuShGA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*JUzn71VxPSDiuPiUGP9iCQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*iaRnR85EaogZY0RCU8w2Lg.png" /></figure><p>and so on..</p><p>And for the messages from the other direction —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*MQnetaMaGi0TJyCZdCfuag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*zRZEnMV1KYvya2jNtOsieQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*g046nztZzVCfBHMTf8b23Q.png" /></figure><p>and so on..</p><p>Thus to compute final marginals —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*sDX0LoVvbq8yYWosFnDjgw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*qBHS_v-iCdam-ujhN4BbRg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*ANKW0j13jKlCq3QeWAaQ3w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*wSd01mm-fm2nZQXB80Ha4Q.png" /></figure><h3>Conclusion:</h3><p>In this article, we’ve added powerful new tools to our arsenal. We looked at Exact Inferencing which would be useful if we have our graph structure ready with variables taking only certain discrete states.</p><p>Variable Elimination taught us to avoid redundant computation by pushing sums inside products. But it had one massive flaw! This way of computation is okay when inferencing on a particular variable but not so good when it came to inferencing on a lot of variables. Suppose we have an oil company and oil at a location depends on lots of factors, and even though we have our Probabilistic Graphical Model ready and everything, we can’t really put it to work in this way because we could need inferencing on a lot of variables.</p><p>That is where Message Passing came in to our rescue, where each node whispered onto the next node information that i had received + information packed into it (If you have played the game <strong><em>Chinese whispers</em></strong>, its a lot like that!)</p><p>But Exact Inferencing can take us only thus far. Being NP-hard (actually #P hard) no clever algorithm could save us from an exponential blowup. But do not worry, we’ll explore Approximate Inferencing in our next article — MCMC sampling, Variational Inference, techniques which trade exactness for tractability. (They are actually really good)</p><p>That’s it then, keep grinding fellow detectives!! Until we are back with more :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=574954c23a74" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Ground Up series(part 5): Hybrid Graphical Models — When directed meets undirected]]></title>
            <link>https://medium.com/@daga.yash/the-ground-up-series-part-5-hybrid-graphical-models-when-directed-meets-undirected-d822860d3190?source=rss-ed1ff4a9d6bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/d822860d3190</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[probabilistic-models]]></category>
            <dc:creator><![CDATA[Yash]]></dc:creator>
            <pubDate>Sat, 20 Dec 2025 19:07:13 GMT</pubDate>
            <atom:updated>2025-12-20T19:07:13.077Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Ground Up series(part 5): Hybrid Graphical Models — When directed meets undirected</h3><p>Voila! Welcome back detectives. In the part 3 and 4 of our series, we went through the how and the when DAGs and UGMs worked — DAGs with their cause-and-effect relationships flowing in one direction (like how Thanos snaps his fingers to wipe out half the universe but the reverse is not true), and UGMs where variables influence each other mutually (remember our example of the beach image generation).</p><p>But here’s the thing! Real life data could be messy. Let me give you a picture.</p><p>Say you are trying to model a conversation in a group chat —</p><ul><li>Who sends the message clearly influences what messages come after.</li><li>But the mood of the conversation? That is a mutual thing. Everyone’s tone affects everyone else’s. There’s no clear direction here.</li></ul><p>What do we do in such a case? Force and fit everything into a DAG and pretend that those mutual influences have a certain sense of direction? Or stuff it all into an UGM and lose the natural flow of messages? Neither feels right, does it?</p><p>One could say that converting DAGs to UGMs or the other way around could be thought of as an idea. But here’s the thing, we are essentially missing out on information that could mean something. We have already discussed about the moralization process and their problems with the head-to-head (or V) configuration. Similarly, while converting UGMs to DAGs there is the square/loop problem. So these processes are not feasible.</p><p>That is where we utilize the power of Factor Graphs.</p><h4>The real object of interest</h4><p>Let us pause and zoom out.</p><p>Every single probabilistic model we’ve studied so far, be it LDA, HMMs, Ising Models, MRFs, they all start with the same objective — Somehow factorizing the joint probability distribution P(X₁, X₂, … Xₙ) while making some assumptions.</p><p>The issue with the joint pdf is simple — The sheer exponential increase in number of parameters as the value of n increases.</p><p>And using different assumptions we are able to lessen the number of parameters substantially by writing the joint pdf as a product of smaller terms.</p><p>In DAGs, we wrote —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*xqduebRkzF1HCjkfhVOrCg.png" /></figure><p>In UGMs we wrote —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*dMjv7PEpaYDR7lQYcAmtgQ.png" /></figure><p>Different syntax, but the essence is the same. Factor graphs allow us to model the probability in a different manner, trying to utilize the best of both worlds — the directed nature of DAGs and the mutual coherence of UGMs.</p><h4>Factor Graph: A formal definition</h4><p>Let us actually see how factor graphs allow us to write the joint probability distribution. Given X = {x₁, x₂, … x𝒹}, {Xₖ}ᵏₖ₌₁ with Xₖ ⊆ X and a function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/170/1*tE2BfLogtdeskF0yprljeQ.png" /></figure><p>the factor graph (FG) is a bipartite graph with a square node for each factor fₖ and a circle node for each variable xᵢ. By normalizing f, we obtain a distribution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/1*p4CVGweLA9QYzDn-lRXxtA.png" /></figure><p>(A bipartite graph is one where the nodes are divided into two layers. RBMs for instance)</p><p>We have one set of ‘vertices node’ for each random variable, and one set for each ‘factor node’. We then draw edges from variable to the factor if that variable appears in the factor. (Doing this gives us an edge as it is a useful )representation for inference which we shall see later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*ApXt3plc13u-5UlOvzwahw.png" /><figcaption><strong>Sample example of a factor graph</strong></figcaption></figure><p>The factor nodes are functions involving only those subsets of variables between which they are drawn. For instance in the above example, factor f𝒸 would be a function of the variables x₁, x₂ and x₃, whereas factor fₐ would be a function of the variable x₁. Similarly, factor fᵦ would be a function of the variables x₂. Thus for the above example we could write —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*9nBs56JIuvWWbmxlLWZEBg.png" /></figure><p>You must be wondering, could we convert our already present DAGs/UGMs using factor graphs? The answer is YES! We just need to define the interactions between the random variables properly as factors such that we are expressing the same joint pdf without any extra interaction between variables than there already were.</p><h4>From DAGs to Factor Graphs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*HCV0U4sobuiXqVTs7ajUBA.png" /></figure><p>Let us first look at DAGs through the lens of factor graphs.</p><p>In a DAG, every node comes equipped with a way to tackle the Conditional Probability Distribution (CPD). We factorize the joint pdf as a product of these CPDs, where each one of them involves a variable and its parents. For example for the above DAG, the joint pdf would be written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*ctQ3gg0EjkXpoA3i9yRSxw.png" /></figure><p>Notice now, each of these is already a factor.</p><p>If we had to make a factor graph for the above DAG, we would it in this manner-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*Ua8LuCz-k5TqGfWBsUY6Qg.png" /></figure><p>Now what would the factors f₁, f₂, f₃ be?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*6WKl8cE-WQEIeIlNM_x2aw.png" /></figure><p>This is one example. We could similarly factor the graphs in this manner. The dependency structure does not go away. The conditional nature is still preserved inside the factor function itself. The factor graph simply refuses to encode how we interpret that dependency, it only encodes that it exists.</p><p>We no longer think in terms of causal arrows. We are thinking in terms of local functions whose product that just define the joint distribution.</p><h4>From UGMs to Factor Graphs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*ozYZrjdfxu635_jvQ1nVqA.png" /><figcaption><strong>Sample example of a UGM</strong></figcaption></figure><p>Now let us look at UGMs. In UGMs, as we know, we define clique potential functions to capture the affinity between the random variables and their values. If we look at the joint distribution for the above example we’ll notice:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*tpsWWUooHNXTGGb4jgs9iw.png" /></figure><p>where Z would be the normalizing constant.</p><p>Again, this is similar to the factors we obtain from the factor graph. We could think of the equivalent factor graph as this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*F8Xf1RpTlpRg0WhAH5QBKg.png" /></figure><p>Similar to the DAGs, we could write the factors in case of UGMs, as long as the joint probability distribution remains the same.</p><p>The distinction between “directed’ and “undirected” was never about probability itself — it was about how chose to describe factorization. But thinking in terms of the factor graphs, that description has been brought down.</p><p>Factor graphs allow both kinds of relationships to coexist peacefully, but by letting factors encode whatever dependency structure is needed. We could represent — conditional probabilities, energy based interactions or even deterministic constraints, the graph stays neutral. What matters is which variables participate in local functions.</p><h3>Conclusion: Closing the case</h3><p>Across DAGs, UGMs, and now Factor Graphs, we’ve essentially seen one thing, fellow detectives! There was just a stylist choice in representing the same thing but in different forms with their own set of assumptions.</p><p>At this point, the structural mystery has been solved. Crime scene has been mapped. The relationships are clear. Every dependency has been accounted for. But there are two main questions that immediately follow —</p><ol><li>Given the data, how do we estimate the parameters in the first place?</li><li>And given the parameters, what can we infer about those unknown variables?</li></ol><p>Both these questions seem innocent, but both turn out to be brutal computations. (As Thanos had rightfully once said: Perfectly balanced, as all things should be :D)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*tlJI4fnMxXVWzYP89f0bsg.png" /></figure><p>In the next part of this series, we will look into the parameter estimation i.e., once we have the data from an unknown process, and once we decide on our model, how do we estimate its parameters.</p><p>Until then, keep grinding fellow detectives! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d822860d3190" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bias Correction in Adam: The Statistical Intuition]]></title>
            <link>https://medium.com/@daga.yash/bias-correction-in-adam-the-statistical-intuition-5908daa01168?source=rss-ed1ff4a9d6bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/5908daa01168</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[adam-optimizer]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Yash]]></dc:creator>
            <pubDate>Fri, 19 Dec 2025 20:16:04 GMT</pubDate>
            <atom:updated>2025-12-19T20:16:04.716Z</atom:updated>
            <content:encoded><![CDATA[<p>Voila Readers!</p><p>We have all come across the very famous <strong>Ada</strong>ptive <strong>M</strong>oment Estimation (or, <strong>Adam </strong>as we might popularly know it). We know it keeps running averages of gradients, adapts learning rates per parameter keeping the history of gradients in mind, and applies bias correction. That last part, we however usually gloss over, and just accept as something that makes Adam work. But, behind all this there is a proper reason why it exists, a subtle statistical issue when we try to learn from noisy, mini-batch gradient descents.</p><p>In this article, we will unwrap the Adam optimizer from first principles and look at the mathematical explanation behind the Bias correction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bYcZ_Pf_GeNVpsvA3PcW7A.png" /><figcaption><strong>A Gemini generated visualization of the Adam optimizer and the Bias correction</strong></figcaption></figure><h4>Why are raw gradients unreliable in the first place?</h4><p>At a very first glance, gradient descent would feel straightforward. Given a loss function L(w) (parameterized by w), we compute its gradient and move the parameters in the direction of steepest descent. If somehow an oracle told us the true gradient of the loss over the entire dataset, then the process would have been direct.</p><p>The catch is, we almost never are able to compute this true gradient. Training using the Vanilla Batch Gradient Descent on a massive dataset (say, a million rows) would require iterating over all examples, just to make maybe one small update on the parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/153/1*Ai3imM2w3FhiBrgFSUj8AQ.png" /><figcaption><strong>Vanilla Batch GD with fixed learning rate eta</strong></figcaption></figure><p>Although, the gradient thus calculated would have been the true estimate. And stochastic gradient descent would make updates for every training example which means that they might oscillate a lot before they converge to the global minimum. So there would be massive chances of overshooting the minima(hence the name ‘stochastic’).</p><p>Instead, we rely on mini-batch gradients. At each step t, we sample a small batch of data from the dataset and compute-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/170/1*XcHUsVtP-Jq43DbPv1Rjcw.png" /></figure><p>where B_t is a randomly chosen mini-batch. The g_t is an estimate of the true gradient, although a noisy one at that.</p><p>If we look at it from a probabilistic point of view, we could think of each mini-batch gradient as a random variable from a distribution such that-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/64/1*mUnvftOphFVvOTlJ4X3OMA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/190/1*yljTwP_CtnIed-2eTIKQLg.png" /></figure><p>This happens because different mini-batches would have different samples from the dataset and thus gradients could vary wildly across them. Thus, as a result even though say the parameters don’t change, two consecutive gradients g_t and g_{t+1} may point in very different directions.</p><p>Raw gradients are therefore high variance signals. Acting on a single gradient step is like making a decision on one noisy measurement.</p><p>Thus, we have been able to plant the idea of — gradients themselves come from a distribution, and that the expectation over such mini-batches would take us to the expectation of the true loss.</p><p>We shall use this as a motivation to move towards the Adam optimizer.</p><h3>The Equations behind Adam</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*jEd2mxxazwMF0SUIlqVogA.png" /><figcaption><strong>The momentum equation, b_1 is generally around 0.9</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*BHTp8dnq81yXJORYUIck5A.png" /><figcaption><strong>The gradient history equation, b_2 is generally around 0.99</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/127/1*orLJlGC4QrsQx0Dfec_4zA.png" /><figcaption><strong>Bias correction for the momentum</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/118/1*Zhq1Yh83BbdfeX91LA5xlw.png" /><figcaption><strong>Bias correction for the gradient history</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*ydVMJ2Jx-XpLuzHEMCzbLA.png" /><figcaption><strong>The final update rule</strong></figcaption></figure><p>Woah, too many equations at one go, right? Don’t worry, we shall unpack all these equations one piece at a time. There are two parts to these equations — the momentum based and the gradient history.</p><h4>Momentum: The first moment equation</h4><p>The Vanilla Gradient Descent update rule which goes like —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/1*KMlQvs84A9xN3280k52-gA.png" /></figure><p>We see that the update rule for the w_{t+1} depends only on the gradient of the parameter w_t. Here, if we visualize a gradient contour that with a flat-er surface, we would realize that the gradient at that step would be tending to 0. This means that the parameters would hardly receive any updates/ updates would be very slow.</p><p>In such a case, we could think of using momentum/history of the parameter to guide the parameters faster through the plateau towards the low lying valley of error (imagine gradients as contours with mountains (higher loss regions) and valleys (lower loss regions) and relatively flat plateaus and gradient descent is like standing at a point and trying to reach the bottom most point of the valley. Thus at each step, we try and take the step that takes us most quickly to the trough.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*lFfC0Vwx99FzyWHAr0vbNA.png" /><figcaption><strong>Gradient contour-Darker shades correspond to valleys/hills and lines very tight or close to each other mean a sharp gradient.</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*WB6H9OzFHo3rk8BHVXNCww.png" /><figcaption><strong>Corresponding gradient surface plotted in 3d. See how darker shade in red corresponds to high error, and darker shade in blue corresponds to less error. We intend to go towards the darker shade of blue to the bottom left starting from any initialization point.</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*jEd2mxxazwMF0SUIlqVogA.png" /></figure><p>Further, we do not want to rely on a single estimate for updating the parameters, hence we accumulate history. We do not want to be hasty and form opinion on the gradient based on a single mini-batch gradient.</p><p>The intuition behind this equation thus lies in the fact that we keep accumulating the history of the gradients at each step, and we weigh them in an exponentially decaying manner.</p><p>The gradient at step t would thus depend the most on gradient at step t-1, second most on gradient at step t-2 and so on towards gradient at step 0.</p><p>Random fluctuations are thus cancelled out, whereas the gradients that repeatedly point in the same direction reinforce each other. The result is a smoother, much more stable update direction often that accelerates convergence compared to the vanilla GD.</p><p>We can think of m_t as Adam’s estimate of the first moment (mean) of the gradient distribution.</p><h4>Adaptive scaling: Tracking the gradient magnitude</h4><p>While we did better on the vanilla GD using momentum, we did not consider that different parameters experience gradients of different magnitudes.</p><p>What does this mean? Let us take an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*9dzniwbI1vrfkzrECKoiyA.png" /></figure><p>If we see the above example of a simple network, given a single point (x,y),</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*RTleKHW3AAK2ZErJ1RMazA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*XNN0qQqLOJFYgOraMQE-mQ.png" /></figure><p>and so on..</p><p>If there are n points, we can just sum the gradients over all the n point to get the total gradient. But what if the feature x_2 is very sparse? (if its value is 0 for most inputs)</p><p>Then gradient with respect to w_2 would be 0 for most inputs and hence w_2 would not get enough updates. If x_2 does happen to be sparse but important as well, we would want to take updates to w_2 more seriously.</p><p>If we think about it, for vanilla SGD, the gradient descent would thus follow a trajectory where it would make most updates first in other directions and then the update in this particular direction. A question thus arises —</p><p>Is there any way we could have different learning rates for different parameters?</p><p>That is precisely where the second equation comes into the picture —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*BHTp8dnq81yXJORYUIck5A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*ydVMJ2Jx-XpLuzHEMCzbLA.png" /></figure><p>Think of the first equation as accumulating the history over the parameters. A sparse feature would have very less accumulated history whereas a dense feature would have a very high accumulated history.</p><p>Now notice the second equation — we divide the learning rate by the square root of this history (we shall get into the correction part in a bit) + a small constant ε(usually set to 1e-8). ε ensures numerical stability and prevents division by zero.</p><p>In essence what we achieve by this scaling is — as the accumulated history of a parameter grows, the learning rate becomes smaller so the updates become smaller for the dense features. On the other hand, for the sparse features, the accumulated history would be small, thus the updates they receive every time they encountered a non-zero value would be big.</p><p>We can think of v_t as Adam’s estimate of the second moment (variance) of the gradient distribution.</p><p>At this point, Adam combines two powerful ideas — momentum and adaptive scaling, to overcome many of the shortcomings of vanilla SGD.</p><h4>Need for Bias Correction</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/127/1*orLJlGC4QrsQx0Dfec_4zA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/118/1*Zhq1Yh83BbdfeX91LA5xlw.png" /></figure><p>Remember how earlier in the article we talked about how we were taking exponentially moving averages for m_t and v_t(Not wanting to rely too much on the current gradient and instead rely on the overall behaviour of the gradients over many timesteps.)</p><p>Another way to look at it would be that we are interested in the expected value of the gradients and not on a single point estimate computed at step t.</p><p>But instead of computing E[gradient w_t] we compute m_t. Ideally we would want —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/154/1*CYCVFcqCovQw7CW5ajG5AA.png" /></figure><p>For convenience, we will denote</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*pmE9QqtBtSGQD1bcRD99vg.png" /></figure><p>Thus, for the First Moment equation we can write</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*r_ffYZDEljrKOQq81wkxig.png" /></figure><p>Considering m_0 = 0 (initializing), we can write —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*7rcDrtNA8ew4rz_otbddMA.png" /></figure><p>Similarly,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*UkVSA-BDVPGb-Wlg3cUckA.png" /></figure><p>Again, using a little bit of expansion we can write,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*DAHVKT-vlwhzFTH5r99_Cw.png" /></figure><p>In general,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*5BFoQZHHiwHNUocaLBGCAA.png" /></figure><p>If we take expectation on both sides,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*bQExa1K1kmIvxmeZLa-zbQ.png" /><figcaption>Beta terms have no dependence hence we can take them outside of the expectation</figcaption></figure><p>(Remember how we had developed an intuition for the gradients to be following a certain distribution from the probabilistic point of view)</p><p>We shall make an assumption here: All g_i’s come from the same distribution that is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/132/1*vzD5-mpQzrVRzqrab2YrtA.png" /></figure><p>This gives us,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*PgMu2Z4XtbhInL9C1vROOA.png" /></figure><p>and further,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*atL-XMQ39cB3MU1V1XQHuA.png" /></figure><p>this reduces to</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/1*ticK6iEx3fFBFU3E2ZWxVA.png" /></figure><p>and finally, we have —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*PHSVfmw451TjGBhtsh4e7w.png" /></figure><p>Hence we apply the bias correction because then the expected value of m_hat_{t} is the same as the expected value of g_t. Similarly, we can show for v_hat_{t}.</p><p>Again, if you do remember, we had set the m_0 = 0, its early estimates systematically underestimate the true moment. This bias is not due to noise in the gradients themselves, but rather a consequence of the initialization of the exponential moving average.</p><p>The bias correction is introduced precisely to counteract this effect.</p><h4>An Intuitive example</h4><p>At t=1, the first moment estimate is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/182/1*FBgQUZkcNcMpSYTXiNGBsQ.png" /></figure><p>If we take the commonly used β = 0.9 for the first moment equation, then</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/142/1*HUkxYV9rOPCCQBMx7P_w2g.png" /></figure><p>At t=2, the first moment estimate is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*jVmziiKmMh8AWkdamwQwoA.png" /></figure><p>Thus, we clearly see how the Adam’s estimate of the gradient magnitude is only 10% of the true gradient at the first step. Even at t=2, we are still heavily damped. So although the gradients themselves may be large, the moving average has only ‘seen’ a handful of them, and therefore is underestimated. This is purely down to the zero initialization.</p><p>But once we divide by the (1-β^t), Adam rescales the moving average so that its expected value matches the true expected gradient</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/154/1*CYCVFcqCovQw7CW5ajG5AA.png" /></figure><p>and like we had seen earlier, this matches the expectation of the loss with respect to parameter w. Without this correction, Adam would unnecessarily take small steps at the most critical phase of training-at the beginning.</p><h3>Conclusion</h3><p>By thus treating mini-batch gradients as random variables and coming from the same distribution, Adam attempts to estimate both the mean and variance of the underlying gradient distribution using exponentially moving averages.</p><p>The bias correction is precisely to counteract the slow learning at the initial stages of training. We have actually gone through the equations of the Adam Optimizer and mathematically proved why it works. So now when you look at the Adam optimizer in any research paper, you know why it works better than the other optimization methods developed on the backbone — Vanilla GD.</p><p>So what are you waiting for? Go over and implement the Adam then from scratch here: <a href="https://www.deep-ml.com/problems/87?ref=yacinelearning"><strong><em>Link</em></strong></a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5908daa01168" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Ground Up series(part 4): Undirected Graphical Models — The Web of Probabilistic Connections]]></title>
            <link>https://medium.com/@daga.yash/the-ground-up-series-part-4-undirected-graphical-models-the-web-of-probabilistic-connections-2f8ef32534bf?source=rss-ed1ff4a9d6bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f8ef32534bf</guid>
            <category><![CDATA[generative-model]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[graphical-model]]></category>
            <category><![CDATA[image-generation]]></category>
            <dc:creator><![CDATA[Yash]]></dc:creator>
            <pubDate>Sat, 10 May 2025 15:46:06 GMT</pubDate>
            <atom:updated>2025-05-10T15:46:06.590Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Ground Up series(part 4): Undirected Graphical Models — The Web of Probabilistic Connections</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a3sAF-hsT8skZFnI-nhnwQ.png" /></figure><p>Voila! Welcome back readers. In the part 3 of our series, we explored how Directed Acyclic Graphs (DAGs) ease out our process of expressing the relationships between the random variables using Conditional Probability Distributions (CPDs). But, if you happen to think about the generation of say, an image of a beach using this particular method, would it be a viable option? Say, you are generating one pixel after another. Do you think that one pixel would be dependent on another pixel and not the other way around?</p><p>Your intuition would say that the pixels are inter-dependent on the neighboring pixels. And, that is correct! The pixels of the sky would tend to have a similar hue, value and saturation that give it a blue-ish tone, whereas the pixels of the rocks would again tend to have similar values amongst themselves, giving them an earthly tone. Only around the edges of two different things would we see a stark contrast between the pixel values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UfmO_xDPlNcm5FDkNnOafQ.png" /><figcaption><strong>Feel the kind of interdependence between the pixel values, contrast around different objects and not necessarily as one dependent on another</strong></figcaption></figure><p>Images we see, are a part of ‘coherent block’ i.e., pixels that are a part of the block have homogenous pixel values but at the very boundary, the adjacent pixels will be different. These pixels aren’t influencing each other in a directional way ( ‘this pixel will cause that pixel to be blue’ etc.) but rather in a collective way to form coherent regions. So, in such a case it makes little sense to condition one pixel based on the previous pixels. The better strategy here would be to condition one pixel based on the ‘neighboring’ pixels.</p><p>It is not necessary that we just want to predict the state of a variable (word/pixels etc.) but rather understand “how” the system behaves as a whole.</p><p>This brings us to the realm of ‘Undirected Graphical Models’ where relationships form a web rather than a chain of cause and effect.</p><h4>What do we want to achieve using a UGM?</h4><ul><li>We wish to account for the local dependencies. Like for example, in an image, pixel values of neighborhood pixels are often correlated as we discussed.</li><li>We wish to capture spatial structures like edges having more importance than independent pixels.</li><li>To avoid specific direction of influence amongst variables.</li></ul><p>That brings us to our first model, that is the Ising Model.</p><h3>The Ising Model: Our first Undirected Graph</h3><p>The roots of the Ising Model date back to explaining the phenomenon of ferromagnetism in statistical mechanics — perfect for understanding how neighboring elements influence each other (beautiful how so many of the generative models like energy based diffusion models that we shall see in upcoming articles are actually derived from physics).</p><h4>Origins in Physics: Understanding Magnetism</h4><p>Imagine a piece of iron. Inside it are countless tiny dipoles (microscopic magnets with north and south poles). When the piece of iron is unmagnetized, these dipoles would point in random directions, canceling each other out. But say, you bring a magnet nearby, then these dipoles would align in the same direction creating a magnet out of ordinary iron.</p><p>But, what causes this alignment? The answer lies in how neighboring dipoles interact with each other.</p><p>The thing is in a ferromagnetic substance like iron, each dipole influences its neighbors, and they in turn influence it. These dipoles prefer to align with their neighbors because this state has a lower energy and that is, in turn, desirable. Thus, what we prefer is dipoles having similar kind of spins to its neighbors and what we do not prefer is dipoles having opposite spins.</p><h4>The Model: Spins and Energy States</h4><p>The Ising model beautifully captures this behavior by representing each of these dipoles as a random variable with two possible states: +1 for a ‘spin up’ state and -1 for a ‘spin down’ state. We define an energy function that is lower when neighboring dipoles have the same spin and higher when they differ.</p><p>Mathematically, for a system with dipoles {S₁,S₂,…Sₙ} we define the energy as —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/152/1*mQ9d0LapcrgTpagJc83gNw.png" /></figure><p>where we sum over all the pair of possible dipoles and J is a constant representing the strength of interaction. J is positive when neighboring spins align and energy is minimized, and vice-versa.</p><p>This leads us to a probability distribution over ‘all possible’ configurations following Boltzmann’s principle (we shall not dive into this here) —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/140/1*u719prCS7FsJ_Av0d2dOiA.png" /></figure><p>where Z is the normalizing constant, k is the Boltzmann’s constant and T is temperature.</p><h4>The Connection with UGMs</h4><p>Returning back to our model, the connection becomes clear. Instead of magnetic dipoles, here we have pixels. Instead of spin up, spin down, we have different color values. Just like how neighboring dipoles prefer to align to have minimum energy, neighboring pixels in natural images tend to have similar values. We shall assign higher probability to pixels having similar values and low probability to pixels having dissimilar values so that they form the edges.</p><p>For a binary image (black and white), we can directly apply the Ising Model by treating each pixel as a dipole with states +1 (say, white) and -1(thus, black). The energy function will reward us for neighboring pixels that have similar value, naturally leading to coherent regions in the image. Thus, we have a small probability of having some sort of a meaningful image rather than just randomly generating noise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ooGCcfuLD4xAMBR9CBelfw.png" /><figcaption><strong>visualize the coherence in most parts of the image and dissimilarity in the edges</strong></figcaption></figure><p>For our beach photo, we would need a more complex model allowing for multiple states (RGB values), but our fundamental principle still remains the same.</p><p>In a DAG we defined the joint pdf as CPDs, but here, we shall define the joint pdf over these random variables where every adjacent random variable contributes as a factor!</p><p>The question however you must be wondering: what should our probability distribution be and how do we define the energy function in our case? Well, we shall have to dive into Gibbs Random Field to understand this!</p><h3>Gibbs Random Field(GRF): Formalizing Our Energy-Based Approach</h3><p>While the Ising Model was designed specifically for situations like magnetic dipoles arranged in some sort of a grid, GRFs give us a framework for any UGM with any type of random variable.</p><p>Gibbs Random Field will help us to represent the factorization of a joint pdf. We represent each variable as a node in an undirected graph. The edges between the nodes represent direct dependencies. It is different from a DAG in the way that here, an edge just indicates that the two random variables are connected in some way. How? Well, let us see.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*I5_pVeQriTK7IpgFh9dCeg.png" /><figcaption><strong>The UGM that we shall use to illustrate the idea of a GRF</strong></figcaption></figure><p>Our idea is to define a joint pdf factored over all the random variables denoted as in nodes.</p><p>The key components of a GRF are —</p><ul><li><strong>Cliques</strong>: A subgraph(a part of a graph that can independently exist as another graph, see ‘C-D-E’, ‘A-B-D-C’) that has every single node connected to each other. In the example above, ‘C-D-E’ is a clique of size 3 (the number of variables) but ‘A-B-D-C’ is not a clique because the diagonals are not connected thus, for ‘A’ it has no connection to ‘D’ and similarly, ‘B’ with ‘C’. Thus, all the nodes are not interconnected, hence even though it is a subgraph it is not a clique. Thus, the maximum size of the clique in the above example is 3 (‘C-D-E’).</li></ul><p>We capture local dependencies in terms of cliques!</p><ul><li><strong>Clique Potential Functions</strong>: For each clique c, we define a potential function ψ𝒸 that assigns a non-negative value to each possible configuration of the variables in the clique.</li></ul><p>Thus, we define the joint pdf over all the variables as —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*JnZPqbE9NPATAqYDBqetgg.png" /></figure><p>where Z is the normalizing constant, which is called the partition function —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/172/1*HTHOtHWqPm7obBgS3n_HIg.png" /><figcaption><strong>basically, summing up over all possible cliques</strong></figcaption></figure><p>In GRF, thus, for the above Undirected Graph, we have,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*-R2pGgBhB-dWUlnp-Rp3hA.png" /><figcaption><strong>Z being the normalizing constant</strong></figcaption></figure><p>where, fᵢ(XY) is the clique potential function between the cliques. (For ‘A-B-D-C’, we will have cliques only of size 2 which will be the edges connecting the adjacent nodes).</p><p>But what should these functions be?</p><p>The beauty, my friend, lies in the fact that these clique potential functions can be any self-declared functions. These need not be probability functions, it can be any function with our desirable properties. Say, for A,B if we want them to take up similar values then we can define the clique function f₁(AB) such that it takes up very high values when A and B are similar and very low values when the two are dissimilar. Thus, for the example of generating images we could assign high values to these clique functions when neighborhood pixels are same and very low values when they are different, thus in this way, keeping the ‘coherent blocks’ in mind while also letting the probability of edges come into the picture, although less, which is what we require.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*sq3eK2Xe8zqyPbMP2OCQkA.png" /><figcaption><strong>Sample example of how we could define the clique potential function f₁(AB)</strong></figcaption></figure><p>Further, what was the need for this normalizing constant Z? Say, we are defining for the above network, then suppose A=B=C=D=E=0 is our desirable quantity so we could have a value =100 for each of our clique potential functions, so you could imagine how big our value in that case would be right? (=10⁶!) Thus the need to normalize.</p><h4>Cliques: The Social Circles of Undirected Graphs</h4><p>I will touch upon cliques in a little more intuitive way here. We first need to understand what subgraphs are in the world of graph theory. It is basically a subset of nodes and edges from the original graph. Just think of it as zooming into a portion of our entire network.</p><p>Formally, if we have a graph G = (V,E) with vertices V and edges E, a subgraph is created by selecting some subset of vertices V’ ⊆ V and some subset of edges E’⊆ E that connects vertices in V’. You can imagine it to be something like this in, say a RGB image intuitively —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*yfW0T0nfQk_PkbsGt5cnxg.png" /></figure><p>In graph theory terms, if in a subgraph we have all the nodes interlinked to one another via edge, it is a clique. Mathematically, a set of vertices C ⊆ V forms a clique if for every pair of vertices u, v ∈ C, there exists an edge (u, v) ∈ E.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*ecQWepjYV4NaWsj7O2QSaA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*WylpHUjHaekfAKHnzNbajA.png" /><figcaption><strong>all the four variables are inter-connected in the first case, hence it is a clique and of size 4. You can think of N c 2 edges, if there are N nodes, there must be N C 2 edges for the subgraph to be a clique.</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*9ijdhEt9Kv73CF-baA-c0g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*Q4o13aHhxmXUmRQVvmOSLg.png" /><figcaption><strong>All the 3 rvs are connected in the second case, hence it is a clique of size 3</strong></figcaption></figure><h4>Maximal Cliques: As Big As They Can Be</h4><p>A particularly important concept is that of a maximal clique. A clique is maximal if we cannot add any more nodes to it while maintaining the property that everyone is connected to everyone else. It’s like saying ‘this friend group is complete — adding anyone else would mean someone in the group doesn’t know the new person.’</p><p>In our graph network above, the maximal clique was of size 3 and it was ‘C-D-E’.</p><p>The best thing here is — We can define our joint pdf as just taking 2 nodes that are connected to each other and writing their particular clique potential function, or we could also utilize the concept of writing the particular clique potential function as a function of the maximal clique. Confusing, right? Let me take you through a particular example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8jnFGcQ--9fP4lEmGv9kUw.png" /><figcaption><strong>So hopefully by now you have understood how to define the clique potential function in a GRF</strong></figcaption></figure><h3>GRF For Ising Model</h3><p>Now that we have understood GRF, we need to understand how to apply it in our Ising Model, because our question of what the probability distribution should be and the definition of the energy function still remain unanswered.</p><p>In a pixel grid, we say that Xᵢ,ⱼ and Xᵢ₊ₐ,ⱼ₊ᵦ are neighboring if a = {−1,0,1} and b = {−1,0,1}. In other words,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*u72IGjuiFK7_0gyaVeN2yQ.png" /><figcaption><strong>see the neighbors for Xᵢ,ⱼ</strong></figcaption></figure><p>We define ψₑ(Xᵢ,ⱼ,Xᵢ₊ₐ,ⱼ₊ᵦ) = exp(I(Xᵢ,ⱼ = Xᵢ₊ₐ,ⱼ₊ᵦ)) where I is the indicator function, and e is the edge between (i, j) and (i + a, j +b).</p><p>The indicator function works in this way: when the neighboring pixel Xᵢ,ⱼ = Xᵢ₊ₐ,ⱼ₊ᵦ is equal then value = 1 thus, when neighboring pixels are equal, ψₑ(Xᵢ,ⱼ,Xᵢ₊ₐ,ⱼ₊ᵦ) = exp(1) = e, and when they are unequal, then I(Xᵢ,ⱼ = Xᵢ₊ₐ,ⱼ₊ᵦ) = 0, thus ψₑ(Xᵢ,ⱼ,Xᵢ₊ₐ,ⱼ₊ᵦ) = exp(I(Xᵢ,ⱼ = Xᵢ₊ₐ,ⱼ₊ᵦ)) = exp(0) = 1. Hence, we apply a higher weightage or probability on neighboring pixels being equal and less when not so.</p><p>The idea remains the same that the edge/clique potential function takes a high value if end-nodes have equal value. This makes coherent structures of X have high probability under distribution P.</p><p>Joint pdf P(X) (probability of a particular image in the entire space of all possible images) in this case remains the same i.e.,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*lhUinrjrAYWXFack3AzFcw.png" /><figcaption><strong>e means over all edges in the graph</strong></figcaption></figure><p>The mode of the configuration i.e., the most likely configuration of the pixels occur when all the pixels are the same.</p><p>We use such techniques in image denoising — smooth out noisy pixel values to create uniform images(think logically as to why this works, we have already discussed it above :D).</p><h3>Markov Random Field(MRF)</h3><p>A MRF is a Gibbs Random Field with special conditional independence properties.</p><p>In a MRF, the random variable represented by node X is independent of the other random variables conditioned on variables represented by the neighbors of X.</p><p>Mathematically, for any variable X and its neighbors N(X):</p><p>X ⊥ Rest of graph | N(X), which means once we know the neighbors of a particular pixel value, that becomes independent of the rest of the entire image. So, to reason about any variable, we only need to consider the local neighborhood, not the entire graph! (Look at how the Markov property has been utilized in a MRF).</p><p>Let us try and re-connect this idea with our beach image. When we examine a blue pixel in the water region, what information do we need to understand its value? Intuitively, if we know the values of its immediate neighbors (which would likely be blue water pixels), are we gaining any additional information by looking at distant pixels in the sky or the rock regions? Answer would be no.</p><p>This is exactly what a MRF formalizes, that every vertex is d-separated from non-neighboring vertices conditioned on the neighbor of that vertex.</p><p>But how does d-separation work in MRF? Let us first take an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*5AjwoiP_ZgPdEzPQ9XdW9A.png" /></figure><p>We follow the same d-separation technique as we did in a DAG, but here without any directional edges. Thus, using d-separation in a MRF is easier.</p><p>For the above GRF, to see if variable A is independent of C given B, we just have to block the variable B, and as there are no paths from A to C thus we can say the two variables A and C are d-separated given B.</p><p>Let us take another example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*EdazKWpE3DhSYBUz4nDwHg.png" /></figure><p>For the above graph, once we block ‘C’, there is no path connecting A to F, thus ‘A’ is independent of ‘F’ given ‘C’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*dyF3jR30UIVZIO8R0x3Drw.png" /></figure><p>Now for the above kind of inference, we need to interpret it as — given at least one of ‘C’ or ‘D’. are at least one of ‘A’, ‘B’ independent of ‘E’.</p><p>For ‘A’, if either of ‘C’, ‘D’ are blocked, then path to ‘E’ is blocked. Thus, d-separation is not possible. The same goes for ‘B’. Thus, they are not d-separated.</p><h4>The Hammersley-Clifford Theorem: Bridging GRFs and MRFs</h4><p>The Hammersley-Clifford Theorem states any Gibbs Random Field based on a positive distribution (where no configuration has zero probability) is also a MRF, and vice-versa.</p><p>So we see that there is a perfect equivalence between —</p><ol><li>Being able to factorize a distribution using clique potential functions (the GRF perspective)</li><li>Having the Markov Property that variables are conditionally independent given their neighbors (the MRF perspective)</li></ol><p>Which means we can switch our thinking in terms of factorization (for defining the model) and conditional independence (for reasoning about the model).</p><h4>The Ising Model as a MRF</h4><p>Interestingly, our Ising Model also naturally satisfies the Markov Property. Every pixel’s value is conditionally independent of all other pixel values given the values of its immediate neighbors.</p><h3>Restricted Boltzmann Machines: A Special Bipartite Model</h3><p>A Restricted Boltzmann Machine is an example of an UGM.</p><p>So far, we’ve looked primarily at UGMs as a grid structure, where the nodes represent the directly observable variables like pixels in an image. But what if we have some important variables in our system that cannot be directly observed?</p><p>That is precisely where RBMs come in. Here, we use a bipartite graph structure — which means that the nodes are divided into two layers (a hidden layer {h} and an observable layer{v}), and edges are only in between the layers, not within a particular layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*L7Y6OH_NTC1_VkHSuEw-KA.png" /><figcaption><strong>A typical RBM, notice how there is no connection amongst the hidden or the visible units.</strong></figcaption></figure><p>But, how do we define edges and weights?</p><p>Each edge between hidden variable Zᵢ and observable variable Xⱼ has a weight corresponding to it, φᵢⱼ. These weights determine the strength of relationship between each hidden node and its corresponding visible node.</p><p>We define the edge potential function in a particular way which is —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*mqSJaB-GYJBJvGjpaDmlbA.png" /></figure><p>The joint pdf is thus calculated in a way similar to the Ising Model.</p><p>The RBM model, just like our Ising Model, uses an energy based formulation to define probabilities, like the GRFs, it factorizes based on cliques and like the MRFs, it enforces the conditional independence properties (between units in the same layer). The only difference lies in the bipartite structure, and the hidden units.</p><p>RBMs are particularly useful in dimensionality reduction, feature learning collaboration filtering. The visible layer could be user recommendations, pixel values for images etc. whereas the hidden layer could be abstract features/patterns.</p><h3>Conclusion: Reconnecting the dots</h3><p>Across all the models we read about, starting from the Ising Model to the GRF, MRF and finally the RBM, we saw a consistent theme — the ability to represent very complex systems through local interactions that ultimately gave rise to global patterns. This is precisely the essence of UGM, how simply using local rules they create an intricate behavior when applied on a network of random variables.</p><p>While we’ve studied the properties here about UGMs, few questions might come up in your mind. Firstly, how do we learn the parameters of these models once we have our data? Like how do we determine what should the optimal weights be in our potential function that can capture the patterns present in those images.</p><p>Secondly, how do we perform inferencing with these models? Like given a noisy image, how do we determine the most likely values of the unobserved parts (something we do in Inpainting of images — that’s quite a wonderful technique :D)</p><p>And last but not least, is there some sort of a connection between DAGs and UGMs? And is there some sort of a model that incorporates both these properties?</p><p>Well worry not because we shall see this in our next blog. So until next time, tata!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f8ef32534bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Ground Up series(part 3): DAGs — The backbone of Probabilistic Reasoning]]></title>
            <link>https://medium.com/@daga.yash/the-ground-up-series-part-3-dags-the-backbone-of-probabilistic-reasoning-c48e6ccdedfa?source=rss-ed1ff4a9d6bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/c48e6ccdedfa</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[directed-acyclic-graph]]></category>
            <category><![CDATA[generative-model]]></category>
            <category><![CDATA[graphical-model]]></category>
            <dc:creator><![CDATA[Yash]]></dc:creator>
            <pubDate>Wed, 07 May 2025 17:16:27 GMT</pubDate>
            <atom:updated>2025-05-07T17:16:27.914Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Ground Up series(part 3): DAGs — The backbone of Probabilistic Reasoning</h3><p>Hey there, fellow detectives! We did manage to track down our elusive thief using the Hidden Markov Model in our previous article, but to question, what magic lied behind the structured representation that made our complex mystery suddenly solvable? Like what was the need to present the case in terms of nodes (the cities in terms of hidden states, the clues as the observable states), edges and a certain set of dependencies between the nodes? Well, worry not because that’s precisely what we’re gonna cover in this article :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Dy5B55OeWS2voY4IeYm3w.png" /><figcaption><strong>Pretty cool :D</strong></figcaption></figure><h4>THE NEED FOR STRUCTURE IN PROBABILITY</h4><p>You, my detective, are trying to solve a mysterious case with dozens of interconnected clues. Each clue could depend on multiple other clues in various ways. But without some kind of an organizational system, the sheer number of these potential relationships between all these clues would be overwhelming for you, right? You would have to track down millions of possible connections!</p><p>This is precisely the challenge that we face when we work with joint probability distributions in the real world. The complexity explodes exponentially as the number of variables increase, making both the representation and computation practically impossible without additional structure.</p><p>Let us say, you have 10 binary variables of clues and the final outcome. To represent the full joint distribution P( X₁, X₂, … X₁₀), we would need 2¹⁰ ( = 1024, as each of these Xᵢ’s can take values of either 0 or 1) probability values in the form of a tabular data. And this is just with 10 variables who just take the values 0 or 1. Now imagine what will happen in case of real-world problems.</p><p>The question that arises is — How can we model such complex systems without this exponential explosion? How can we make it computationally tractable?</p><h4>Independence to our rescue?</h4><p>One idea would be to consider independence amongst all variables (in our case, the clues). In other words,</p><p>P( X₁, X₂, … Xₙ) = P(X₁) × P(X₂)… × P(Xₙ)</p><p>This would reduce our 1024 parameter model to just 10 parameters! Wohoo — But hold on, there is a massive flaw in this. We are considering that none of the clues have any relation with each other or to put it simply, the variables are fully independent. The clues could well be, and in most cases are interconnected to each other. That is how detectives solve the case. Thus, our model would be grossly inaccurate in real life scenarios.</p><h4>Conditional Independence: The Middle Ground</h4><p>What we need is some sort of a middle ground between the extremes of ‘everything depends on everything’ and ‘nothing depends on anything’. This is where conditional independence becomes crucial:</p><p>But what do we mean by it?</p><p>Two random variables say X and Y are “conditionally independent” given Z iff P(X,Y|Z) = P(X|Z) × P(Y|Z). (iff means ‘if and only if’.)</p><p>In other words, once we know Z, the value of X gives us no additional information about Y and vice versa.</p><p>You might be wondering what difference does this make if we do not consider X and Y as conditionally independent? Well, in that case we would write P(X,Y|Z) = P(X|Z) × P(Y|X,Z).</p><p>So, in case of graphical models, we model the relationships between the variables in terms of conditional independence, a particular variable depends only and only on a set of given variables and not all. Thus, we occupy the middle ground by factorization.</p><h3>The Graphical Solution</h3><p>We represent these factorizations in terms of graph structures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*MP5-0ceBd6abQvW9czOW8A.png" /><figcaption><strong>Sample example of representation of graphical models (An Undirected Graphical Model on the left vs a DAG on the right)</strong></figcaption></figure><p>Each random variable is shown as a node/vertex, and vertices V are connected by edges. The structure of the graph encodes precisely which conditional independence assumptions we are making.</p><h3>The Two Families: Directed and Undirected Models</h3><p>This brings us to the two main families of graphical models:</p><ol><li><strong>Directed Graphical Models (Bayesian Networks) or DAGs </strong>: These use directed edges (arrows) to represent relationships between variables. In the example above, variable Y depends on X and Z. The directionality is important in this case, as random variables X and Z do not depend on anyone (they are thus called parent nodes). Recall how we showed directionality in LDA and HMM.</li><li><strong>Undirected Graphical Models (Markov Networks)</strong> : These use undirected edges between random variables to represent constraints between variables. Suppose you are generating a grayscale 28 * 28 image where each pixel can take on only 0/1. So when generating a particular pixel, it would normally depend on the values of the surrounding pixels right? But is there a directionality in this case, that the other pixel does not depend on this one? Obviously not. Here, there is a mutual dependence between random variables, with no sense of directionality.</li></ol><p><em>“But, why DAGs?” </em>To put it, DAGs guarantee us a coherent joint probability distribution in terms of conditional probability distributions(CPDs) something undirected models lack.</p><p>And, how do we define a DAG?</p><h3>A formal definition of DAG —</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*coIOO2dR0G2aIlcJLmVPeQ.png" /><figcaption><strong>Sample example of a DAG that we will use to explain how to define the joint pdf in such a case</strong></figcaption></figure><p>At each vertex v ∈ V (the set of vertices, here {A,B,C} ), we have a conditional pdf P(v | Pa.(v)) defined.(where Pa.(v) refers to the set of parent nodes of v)</p><p>Thus the joint pdf P(V) can be represented as —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/212/1*L0h6OIPGxZlCAvwqbZMStQ.png" /></figure><p>Like for, in the example above, Pa.(A) = Φ,</p><p>Pa.(B) = Φ,</p><p>Pa.(C) = {A,B}</p><p>Thus, P(A,B,C) = P(A).P(B).P(C|A,B)</p><p>Notice, how we assume independence relations here! If we just follow the rules of probability P(A,B,C) = P(A).P(B|A).P(C|A,B). In other words, B is independent of A, but if we have observed C then the value of B no longer remains independent of A. This is exactly the power of DAGs!</p><p>Let us see some more examples of DAGs with how they factorize the joint pdf encapsulating certain independence relations —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*sxhaCZ2Cni_0SepQgcHtOg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*cPqxUMXmQK_Au_OEKsoNDw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*0FyE9gnpu7SWbFycMnVbAA.png" /><figcaption><strong>The first one is called Head-to-head or collider/v structure and the second one is called tail-tail configuration.</strong></figcaption></figure><p>Notice how the entire system changes as we change the directionality of the arrows. The variables remain the same, all we are doing is changing directionality and/or adding edges in between and,</p><p>Voila! We give it a whole new meaning.</p><p>Let us take the example of a fuel system to clarify things.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*NZ7vqhxtFHO73O_jtgQOSQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*EjrwwuhRNRG64CfKyXuOig.png" /><figcaption><strong>B here represents battery prior probabilities, F represents fuel prior probabilities, and G represents gauge probabilities</strong></figcaption></figure><p>Basically, gauge represents whether or not the car runs, and that depends on the battery and the fuel of the car. Suppose we are only able to observe the gauge (whether or not the car’s working or not). If G =0 and if we somehow happen to also see that B = 1, then saying F = 0 would not be a very bad option in terms of probability. (think intuitively here) Thus, once we observe G we can see there is a certain dependence between the variables B and F, but having not known the value of G, we cannot make any inferences about the values of B and F, that is they are totally independent of each other.</p><p>Now, let us say that the gauge reads empty (G = 0). Our prior belief about F says that P(F=0) = 0.1 i.e., there is a 10% chance of the fuel tank being empty.</p><p>Having observed G = 0, our prior belief about F would update as —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*FUm5o4zUR3b5eBE9FkNblQ.png" /></figure><p>where,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*XEYIf2E5KyBUupYIFPxX7g.png" /><figcaption><strong>Writing out the joint pdf of the distribution and marginalize over B,F to get P(G)</strong></figcaption></figure><p>and,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*693GZpCurxQq1s0-j-vhcw.png" /></figure><p>Therefore, P(F = 0 | G = 0) = 0.257, or in other words, the probability of the fuel tank being empty is now 25.7% after the gauge reads empty. Thus, this is how our ‘belief’ gets ‘updated’ as we ‘observe’ data. (Bayes learning)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*FRefQEood2BIqMSmBtBdFA.png" /><figcaption><strong>Important to note: This is not a DAG because of its cyclic nature.</strong></figcaption></figure><h3>Conditional Independence</h3><p>A probability distribution P(X₁, X₂, … Xₙ) may entail various conditional independence relations which might not be captured in a graph. Like for example, you have a joint pdf and you construct a Bayesian Network G out of it. It may very well be possible that our network G does not capture all the conditional independence relations invoked by the joint pdf P, or it could also be possible that G captures some extra conditional independence relations that are not implied by P.</p><p>But how do we determine which conditional independence relations are encoded by a graph? This is where the concept of d-separation becomes crucial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*IadLlDKSwraCNT1VlofO0g.png" /></figure><p>D-separation gives us a graphical criterion to read conditional independence directly from the structure of a DAG.</p><p>A pair of vertices, A and B are d-separated conditioned on a set of vertices (say C) iff every (undirected) path between them is blocked i.e.,</p><ul><li>If for any v ∈ C on the path, the configuration is either head-to-tail or tail-to-tail, OR</li><li>If for every v on the path with head-to-head configuration, neither v nor its descendants are in C</li></ul><p>Let us use a graph to understand the same —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*RfVlygieccXbO0FPejGbXQ.png" /><figcaption><strong>a and b are not d-separated given c</strong></figcaption></figure><p>‘From’ the above graph, we can write the joint pdf P(a, b, c, e, f) = P(a). P(f). P(b|f). P(e|a,f). P(c|e). Now, this graph certainly does not tell us about the conditional independence of ‘a’ and ‘b’ given ‘c’. But what if the joint distribution were to actually give us that information? Here, in such cases, we use the d-separation method to find additional independence relations apart from the obvious ones, from a Bayesian Network G.</p><p>For the above case, ‘a’ is not d-separated from ‘b’ given ‘c’. Why? Let us check from the 2 conditions that we provided.</p><ul><li>First condition says — If for any v ∈ C on the path, the configuration is either head-to-tail or tail-to-tail, then A and B are d-separated given C. Here, ‘c’ does not obey this condition.</li><li>Second condition says —If for every v on the path with head-to-head configuration, neither v nor its descendants are in C. Even this condition is failed because, ‘e’ lying in the path has a head to head configuration and ‘c’ being it’s child node which lies in C.</li></ul><p>This proves that ‘a’ and ‘b’ are not d-separated given ‘c’.</p><p>Let us look at another example to clarify things a lot better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*UQckqhQxKa1BY2uasv65DQ.png" /><figcaption><strong>a and b are d-separated given f</strong></figcaption></figure><p>For the above graph, ‘a’ is d-separated from ‘b’ given ‘f’. Why? Let us see again.</p><ul><li>First condition says — If for any v ∈ C on the path, the configuration is either head-to-tail or tail-to-tail, then A and B are d-separated given C. Here, f ∈ C and has a tail-to-tail configuration, thus the first condition is satisfied.</li></ul><p>This proves that ‘a’ and ‘b’ are d-separated given ‘f’.</p><h4>D-Maps and I-Maps</h4><p>Suppose we are given a joint pdf P(X₁, X₂, … Xₙ) and we decide to draw a Bayesian Network G corresponding to the joint pdf to represent it in the form of a graph. If every Xᵢ ⊥ Xⱼ | X𝒸 in P(X₁, X₂, … Xₙ) implies Vᵢ and Vⱼ are d-separated in G with respect to V𝒸, that is reflected in the Bayesian Network G, then we say that G is a D-Map for P. Or in other words, G has all the conditional independence relations in terms of d-separations that the joint pdf P tells, and it might also suggest some extra relations between the random variables which are not true. Think like P is how the variables are actually related in reality and G represents our understanding of how variables influence each other.</p><p>If Vᵢ and Vⱼ are d-separated in our Bayesian Network G with respect to V𝒸 implies Xᵢ ⊥ Xⱼ | X𝒸 with respect to P, then we say that G is an I-Map for P. That is, there are some relations that are in reality but are not captured by the graph.</p><p>If both D and I-Map hold, then we call G a ‘Perfect Map’ for P.</p><p>So basically whenever we were drawing a DAG and then writing the factorization according to it, we are drawing an I-map for P, because there may be certain relations in reality that we fail to capture.</p><p>Let us see below with an example —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*req2jvyAI0aXNHOVtN22NA.png" /></figure><p>Supposedly we know the joint pdf is P(A, B) = P(A).P(B). We decide to draw a BN G to represent the above pdf and we come up a BN as the one above. According to the graph, P(A,B) = P(A).P(B|A). Here, our graph misses an extra independence relation of B being independent of A, and thus G becomes an I-Map for P.</p><p><strong>Theorem :</strong> If A and B are any two random variables such that B is not an ancestor of A with respect to the perfect map G, then A ⊥ B|C where C is the set of ancestors of A with respect to G. Let us see with an example —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*52zxqgBuU_8dH_kFN1lJoA.png" /><figcaption><strong>Hope this clears out :D</strong></figcaption></figure><h3>Types of DAGs: The Many Faces of Directed Graphical Models</h3><p>Now that we have covered the fundamentals of DAGs, let us explore the rich ecosystem of specialized DAG models. Just like how Sekiro uses different prosthetic tools to take down different bosses and mini-bosses, there are specialized DAG structures for different modeling challenges.</p><ul><li><strong>Hidden Markov Models (HMMs) —</strong> For data that has sequential nature like speech, text, or financial time series, these DAGs provide a powerful framework. (Head over to the part 2 of this series to have a detailed hands-on building HMM from scratch)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vFWg5pH-XGd5mHvT_1cC1A.jpeg" /><figcaption><strong>The graphical representation of a HMM</strong></figcaption></figure><ul><li><strong>Latent Variable Allocation(LDA)</strong>— DAG models that incorporate latent(unobserved) variables which represent hidden factors. (Head over to our part 1 of our series to have a detailed hands-on building LDA from scratch)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*-IHB_UANkSFICbHJWnrY2Q.jpeg" /><figcaption><strong>Plate notation for a LDA</strong></figcaption></figure><ul><li><strong>Naive Bayes Models </strong>— Here, a single ‘class’ variable is the parent of all other ‘feature’ variables. Despite the strong (and often incorrect) assumption that all features are conditionally independent given the class, it works surprisingly well for text classification, spam filtering.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*b3KNOV3lEEMjPM_V_jci0g.png" /><figcaption><strong>Source : Probabilistic Graphical Model by Koller Friedman</strong></figcaption></figure><ul><li><strong>Dynamic Bayesian Networks (DBNs) </strong>—These models extend HMMs to allow richer structures within each time slice. Instead of a single hidden state variable, each time slice can contain multiple interacting variables. For instance, in human motion tracking, one time slice might include variables for joint positions, velocities, and accelerations. DBNs can model complex temporal processes like gene regulatory networks, robot movement, or financial markets where multiple factors interact over time.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*1f-B-3kM6Ki8EBn9cxJzuA.png" /></figure><ul><li><strong>Gaussian Bayesian Networks</strong> — When dealing with continuous variables, GBNs assume variables follow normal distributions, with means that are linear functions of their parents. This allows for efficient inference and provides a bridge to linear models familiar from classical statistics. A financial modeling example might use a GBN to represent how economic indicators influence stock prices, capturing both direct and indirect pathways of influence.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*E9eObIxLFixyh9i3IN3Xiw.png" /><figcaption><strong>Graphical representation of GBN. Notice how every variable assumes a normal distribution</strong></figcaption></figure><h3>Conclusion: Our DAG Journey Continues</h3><p>So detective, we’ve come quite a way on our journey through the world of Directed Acyclic Graphs! We started with a very fundamental problem: how to represent complex probabilistic relationships without an exponential overflow of parameters, where we discovered the elegant middle ground of our graphical models.</p><p>We then saw how DAGs give us a visual language for encoding conditional independence by allowing us to factorize joint pdfs into conditional probability distributions(CPDs). We then learned how to read these independence relationships directly from graph structures using d-separation and explored the relationship between graphs and distributions through concepts like I-Maps, D-Maps, and Perfect maps. We then surveyed the rich ecosystem of our specialized DAG models from HMM to LDA and GBNs.</p><p>The next part is where it truly gets interesting. Having the structure of relationships is ‘only’ half the mystery solved. The natural questions that follow are — How do we actually use this graph to answer ‘queries’? How do we update our beliefs when we observe ‘evidence’? And how do we learn the parameters of these models from data? Don’t worry buddy, I’ve got you covered. We shall be diving into the fascinating world of inference and parameter estimation in DAGs.</p><p>Imagine we’re investigating a suspected crime scene. We have a DAG representing relationships between suspects, crime and evidence. We have just discovered a new piece of evidence at a crime scene, how does this update our beliefs about who committed the crime? When we observe patterns of criminal behaviour over time, how do we refine our understanding of the relationships in our network? These are the exact kinds of questions inferencing and parameter estimation allow us to answer. The mystery continues next in our seires where we’ll turn these graphical structures into problem solving machines.</p><p>Until then, happy investigating my detectives! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c48e6ccdedfa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Ground Up series(part 2): The Secrets Behind Hidden Markov Models (HMM)]]></title>
            <link>https://medium.com/@daga.yash/the-ground-up-series-part-2-the-secrets-behind-hidden-markov-models-hmm-f2c725296896?source=rss-ed1ff4a9d6bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2c725296896</guid>
            <category><![CDATA[graphical-model]]></category>
            <category><![CDATA[generative-model]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[hidden-markov-models]]></category>
            <dc:creator><![CDATA[Yash]]></dc:creator>
            <pubDate>Sat, 22 Mar 2025 06:39:22 GMT</pubDate>
            <atom:updated>2025-03-22T06:40:17.613Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey there! So imagine you are a detective trying to track the movements of a thief who has been moving between different cities each day. You are never able to directly see the thief, but each morning, you receive a letter from whichever city they are currently visiting. Now, the letters don’t tell you the city name, but they contain subtle clues regarding the local weather, descriptions of the local cuisine of the place or mentions of famous landmarks or stuff that you could easily relate to.</p><p>After collecting these letters for weeks, you start noticing patterns. When the thief is in Milan, the letters often mention about Pizzas, Risottos and AC Milan. The letters from Tokyo often describe cherry blossoms and sushi. The ones from Edinburgh mention about the beautiful architecture and the old fashioned streets.</p><p>You also start noticing transition patterns. The thief rarely jumps from Tokyo to Milan — maybe they stop at Mumbai first. After Milan, they frequently go to Edinburgh and from Edinburgh, they head to Tokyo to complete the circuit.</p><p>This is exactly how a Hidden Markov Model works:</p><ul><li>The “<em>hidden (or latent) states</em>” are the thief’s actual locations (Mumbai, Tokyo, Edinburgh, Milan) which you are not observing directly.</li><li>The “<em>observations</em>” (or as you may call it the observed variables) are the clues in the letters (which mention about food, weather descriptions, landmark references etc.).</li><li>The “<em>emission probabilities</em>” represent how likely certain clues appear from each city ( there’s a 80% chance of the mention of Pizzas when the thief is in Milan, a 65% chance of mention of Susi when in Tokyo)</li><li>The “<em>transition probabilities</em>” capture the thief’s movement patterns (say a 75% chance of going from Edinburgh to Tokyo, a 20% chance of going from Mumbai directly to Milan).</li></ul><p>So once you unleash the power of HMM, after collecting enough letters, you, the detective could:</p><ul><li>Predict the thief’s current location based on a given day’s letters content (our evaluation problem)</li><li>Construct the most likely travel route over the past month or so (our decoding problem),</li><li>Learn about cities that you might have never visited by analyzing patterns in the letters (our learning problem).</li></ul><p>So, that’s how much we can learn by leveraging the use of a Hidden Markov Model. Basically, we observe certain variables and they might be somehow linked to each other, but in an indirect way. The hidden states that link these observed variables can be inferred using a HMM.</p><p>Quite a big story, right? You could well be confused at this point. Let us begin from the beginning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*8FQXztUo3mxHziWrSWp2gg.gif" /><figcaption><strong>I promise it won’t be the same after this blog :D</strong></figcaption></figure><h4>A brief idea on the Markov Process</h4><p>Formally, a Markov Process is a stochastic model describing a sequence of possible events where the probability of ‘<em>each</em>’ event depends ‘<em>only and only on the state of the previous event’</em>.</p><p>If Zₜ is the state (the values a particular state can take) of the system at time t then,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*ACqTV1EaYZCGG6oq55KBwQ.png" /></figure><p>would actually reveal the probability of being in state S𝓏 given all the previous observations. But, given that Zₜ follows a Markov Process the equation reduces to —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/1*YKtE6VcudpbacX6gRulmXw.png" /></figure><p>This is what we call a “<em>memoryless property</em>”.</p><p>Let me give you an example,</p><p>The text prediction on your mobile phones’ keyboard. It’s quite intriguing right, when we type one word and a next word automatically shows up as suggestion? Yep, that’s exactly a Markov Process in action!</p><p>So suppose, the current word is ‘I’, then there’s a 40% chance the next word will be ‘am’, a 35% chance it’ll be ‘will’, and a 25% chance it’ll be ‘think’.</p><p>Connecting back to our original example, the thief’s movement between cities follows a similar pattern. There’s a certain probability he’ll move from Milan to Edinburgh, or from Tokyo to Mumbai. His next location just depends on his current location, and not the location he was in, a week or a month prior. This is another Markov Process at work.</p><h4>Observable Markov Models: Where everything is visible</h4><p>Here we are observing the results of the world we are modelling which is creating state Sᵢ at time tᵢ. The Markov Property still holds here.</p><p>The beauty of Observable Markov Models is their simplicity. If everything is visible then the calculations become straightforward. It’s when states become hidden that things get more interesting, and that’s where we’re headed next!</p><h4>Hidden Markov Models: Unveiling the mystery</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*OIJBkOqCKko-Vf79XFBMvg.png" /><figcaption><strong>No but seriously, what was the need to hide :(</strong></figcaption></figure><p>Now that you have a brief understanding of the Markov Property and the Observable Markov Models, we arrive at the heart of our investigation — Hidden Markov Models. Unlike the Observable Markov Models where every state is visible and the inferencing is done on that particular variable itself, HMMs introduce a layer of mystery by adding states that are hidden from view. We only observe indirect hints about them.</p><p>To formally define a HMM, we need 5 parameters included in a tuple, μ = (X, Y, A, B, π) where,</p><ul><li>X = {x₁, x₂, …, xₙ}: The set of hidden states at a particular time stamp t,</li><li>Y = {y₁, y₂, …, yₘ}: The set of possible observations at a particular time stamp t (which could also be sampled from a continuous distribution. Here, we take the example of a discrete HMM. The code implementation uses a normal distribution of Y|X),</li><li><strong>A</strong> = {aᵢⱼ}: The state transition probability matrix, where aᵢⱼ = P(state j at t+1 | state i at t),</li><li><strong>B</strong> = {bⱼ(k)}: The emission probability matrix, where bⱼ(k) = P(observation k | state j),</li><li><strong>π</strong> = {πᵢ}: The initial state probability distribution.</li></ul><p>In simpler terms? We have a system that moves between hidden states according to transition probabilities, and at each state, it generates observable outputs according to the emission probabilities.</p><p>Still confused, right? Let me show you how this looks —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Huxd_YRDTY0jkaXiokqIig.png" /><figcaption><strong>The graphical representation of a HMM</strong></figcaption></figure><p>A HMM is also an example of a Directed Graphical Model, where we represent the joint probability distribution in terms of conditional independence between the variables which are shown via edges.</p><p>The joint probability distribution in case of a HMM thus factorizes as —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*ogc3JK2rdSMOZzzqMsNmng.png" /><figcaption><strong>The joint pdf in a HMM model</strong></figcaption></figure><p>where,</p><ul><li><strong>Initialization distribution</strong><em> : </em>P(X₁) is called the “<em>initialization distribution</em>” such that<strong> πᵢ ~ Dirichlet(α);</strong></li><li><strong>state transition probability (and matrix) :</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/121/1*MXdLHJh-nxIGCUMDIEUi0A.png" /></figure><p>the above term is called the “<em>state transition distribution”</em> and is defined using the matrix A with elements as —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*7qc3q070DGDEJrYbOKgx1w.png" /><figcaption><strong>This holds such that 1 ≤ i, j ≤ N</strong></figcaption></figure><p>such that,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/81/1*jmHIhFE1u9H3ILIg_3bNkA.png" /></figure><p>(from a given state, probability of all the ways it can reach another state sums up to 1) In other words, “What is the probability of the hidden state transition to j, given that the system is currently in hidden state i?”;</p><ul><li><strong>Emission probability (and matrix):</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/93/1*Uwp7WHMyHgTd2OJJ4UDsYg.png" /></figure><p>the above term is called the “<em>emission distribution</em>” and is defined using the matrix B with elements as —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*dCZ2vrb8RFG112duiDjZpg.png" /></figure><p>where,</p><ol><li>Yₜ represents the observation at time step t,</li><li>yₖ represents the k-th possible observation from our observation set,</li><li>Xₜ represents the hidden state at time t,</li><li>sⱼ is the j-th state from our state space.</li></ol><p>In other words, it answers: “What is the probability of seeing observation k, given that the system is currently in hidden state j?”</p><p>Let me give you an example. Imagine you are confined in a windowless room for several days. You have no way to look outside at the weather, but only have a thermometer to measure the room temperature. And you are given this information that the weather outside can only be in one of the three states: Sunny, Cloudy, or Rainy.</p><p>Thus,</p><ul><li>The latent variable (or the hidden state as you might call it informally) is the actual weather outside which is unobserved,</li><li>The thermometer readings are the observations which we directly see,</li><li>The transition matrix is how the weather changes from day to day and,</li><li>The emission matrix is how the temperature relates to the outside weather.</li></ul><p>For example, the state transition matrix could look something like —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*dHu-nR4TtmeP4ZizwyKznA.png" /><figcaption><strong>State transition matrix which we assume here to be time independent</strong></figcaption></figure><p>Graphically we could also represent it something like this —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ZGmseoBBcIDadNvcZon8g.png" /></figure><p>The emission probabilities could look something like —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hM8n1tGKWlO1FCKJquJLRw.png" /></figure><p>This is an example of a discrete HMM, where the Hidden HMM has T hidden states, but they typically correspond to something we know about the world. In other words, the states are ergodic i.e., move from one state to another is possible.</p><p>Thus to generate observations —</p><ul><li><strong>Initialization</strong>: Choose X₁ = Sᵢ according to the initial state distribution πᵢ (initialization),</li><li>Set t = 1 (time stamp),</li><li><strong>Generate observation</strong>: Choose Yₜ = Vₖ according to B i.e., bᵢ(k) [observation at t = t according to the state you are in, and that will depend on the probability distribution of that state],</li><li><strong>Transition</strong>: Transit to a new state Xₜ₊₁ = Sⱼ according to A i.e., aᵢⱼ.</li><li><strong>Increment time</strong>: Set t = t + 1 repeat until t &gt; T.</li></ul><p>So basically, an Observable Markov Model is a special case of the Hidden Markov Model where the observation distribution has just one non-zero entry.</p><p>This is fine but you must be wondering, “<em>But how do we know what values to initialize the parameters A, B and π so that the likelihood of observing the data is maximized, and how do we know the hidden states and even the path of the hidden states?</em>” This brings us to the three fundamental problems of HMMs as you will see below, and how we tackle them.</p><h4>The Three Fundamental Problems of HMMs:</h4><p>Once we have our observation sequence, we typically want to answer to three questions, which correspond to three fundamental problems in HMMs:</p><ol><li><strong>Evaluation</strong>: Given the parameters A, B and π, how likely are we supposed to see the sequence of observation we are seeing?</li><li><strong>Decoding</strong>: What are the sequence of states that ‘<em>best</em>’ explain the sequence of observations we see?</li><li><strong>Inference</strong>: Given the set of observations, what are the model parameters that would ‘<em>best</em>’ generate them?</li></ol><h3>The evaluation problem: The Forward-Backward Algorithm</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Huxd_YRDTY0jkaXiokqIig.png" /></figure><p>Imagine you’re building a system to recognize whether someone said ‘Hi’ or ‘Bye’ based on a noisy audio. The problem is that the audio features don’t perfectly map to letters, for example, sometimes an “H” sounds like a “B”, and vice versa(because of the background noise or some other reason).</p><p>Let’s use a tiny HMM, where :</p><ul><li>Our Hidden states are the actual letters spoken (H, I, B, Y, E) and,</li><li>Observations: Audio feature clusters (labeled 1, 2, 3),</li><li>The emission probabilities are: P(1|H) = 0.7, P(2|H) = 0.2, P(3|H) = 0.1; P(1|I) = 0.1, P(2|I) = 0.8, P(3|I) = 0.1 ; P(1|B) = 0.6, P(2|B) = 0.1, P(3|B) = 0.3 ; P(1|Y) = 0.1, P(2|Y) = 0.1, P(3|Y) = 0.8 ; P(1|E) = 0.2, P(2|E) = 0.7, P(3|E) = 0.1.</li><li>Initialization π = [0.5 for H, 0.1 for I, 0.3 for B, 0.07 for Y, 0.03 for E]</li><li>Transition probabilities are: P(H→I) = 1.0, P(B→Y) = 0.9, P(B→E) = 0.1, P(Y→E) = 1.0(rest transition probabilities are 0).</li></ul><p>Now imagine we observe the sequence [1, 2]. What’s the probability this is ‘Hi’?</p><p>Naively, we could calculate: P(H) × P(1|H) × P(I|H) × P(2|I) = 0.5 × 0.7 × 1.0 × 0.8 = 0.28</p><p>But what if we observe a longer sequence like [1, 2, 1, 3, 2]? Calculating “<strong>every possible path</strong>” becomes unwieldy. The Forward-Backward algorithm gives us an efficient way to handle this complexity by breaking the problem into smaller subproblems and avoiding repetitive calculations. Let us see how this algorithm comes to our rescue! (well it really does)</p><p>Our goal is to infer P(X|Y) (that is, given the observations, what is the probability of the hidden variables taking on certain values), but we usually care about P(Xₜ|Y) (given the observations, what is the probability of any particular latent variable Xₜ taking on a certain value).</p><p>One way to think about it could be —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/165/1*phk86Fv_TIFv9R1Q_OihoQ.png" /><figcaption><strong>where P(Y) is constant</strong></figcaption></figure><p>where X = {X₁, X₂, …, Xₜ}, Y = {Y₁, Y₂, …, Yₜ}, 1 ≤ Xₜ ≤ T.</p><p>P(Y) is the normalizing constant which will be summed up over all the X.</p><p>Thus, we can write,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tDjHA0Wfrn4A5ed9ywQWMQ.png" /></figure><p>As discussed above, this would be very computationally expensive. Why? Suppose say, we have a Hidden Markov Chain of length 100. When computing X₅, we have to marginalize all the products,</p><p>P(X₁).P(Y₁|X₁).P(X₂|X₁)…P(X₅|X₄).P(Y₅|X₅)…P(X₁₀₀|X₉₉).P(Y₁₀₀|X₁₀₀) over every X except X₅.</p><p>When computing say X₇, we have to marginalize all the products</p><p>P(X₁).P(Y₁|X₁).P(X₂|X₁)…P(X₇|X₆).P(Y₇|X₇)…P(X₁₀₀|X₉₉).P(Y₁₀₀|X₁₀₀) over evert X except X₇.</p><p>Thus, we can see a pattern. There are a lot of repeated calculations that are taking place. Further, if the length of the chain becomes too long, then it becomes computationally very expensive to marginalize over all the X’s except the particular X we want to infer. Mathematically,</p><p>There are N^T state sequences (N being the number of states a particular X can take on, and T being the length of the chain), and total multiplications per state are 2T-1.</p><p>Thus, total number of operations = (2T-1)*N^T + (N^T-1), which is of the order O(TN^T).</p><p><strong>[Quick Note</strong>: Marginalizing means summing or integrating over a particular random variable to remove it from consideration whilst preserving the probability information about the remaining variables. Essentially, if we are just given a basic Directed Graphical Model something like this —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*i3Xn0qYmHTUA2QwXG_XtzA.png" /></figure><p>So, if we are marginalizing over X₁, we are essentially finding all the ways X₁ reaches X₂ weighted by the probability of that each path. In mathematical terms, the marginal distribution of X₂ would be P(X₂) = ∑ₓ₁ P(X₁=x₁, X₂). Our goal was to find the distribution of X₂ alone.]</p><p>Thus, here comes the Forward-Backward Algorithm to ease the complexity of the inference P(Xₜ|Y). In simpler terms, we want to find out the most likely state a particular latent variable is in, given the parameters and the observations. Let us see how the Forward-Backward Algorithm eases out calculations.</p><p>We break our requirement of inferencing P(Xₜ|Y) into two parts —</p><ol><li><strong>α</strong>ₜ(i) = P(Y₁, Y₂,… Yₜ, Xₜ = Sᵢ | λ<strong>) </strong>where λ = [A,B,π].</li><li>βₜ(i) = P(Yₜ₊₁, Yₜ₊₂, … Y_{T}| Xₜ = Sᵢ , <strong>λ</strong>)</li></ol><p>Let us first take a look at <strong>α</strong>ₜ(i) which essentially forms the crux of the Forward Algorithm.</p><p><strong>α</strong>ₜ(i) = P(Y₁, Y₂,… Yₜ, Xₜ = Sᵢ | λ<strong>) —</strong> essentially what it implies is the probability of seeing the partial observation sequence upto time step t and being in state i at time t.</p><p>Instead of calculating the probabilities like we did previously time and again, here we are storing the information of a particular time step and passing all the information it has received from the previous time steps, onto the next time step. Confusing? Let me first formally define how we calculate <strong>α</strong>ₜ and then move towards a visualization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZxG0xEDQPPzOycRdaGgKtg.png" /></figure><p>Thus, we recursively calculate the value of <strong>α</strong>ₜ. The time complexity in this case equals O(N²T).</p><p>To represent in terms of the parameters,</p><p>we can write the base case as,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*ISJqNmwVMqKP3nQkGm0pqg.png" /></figure><p>and the inductive step becomes,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*nsEWJi03OvMAUL0BPI74Kw.png" /></figure><p>In other words, sum of all different ways of getting to state j given our observed sequence until the previous time step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*x6I0XyNYWnm8vFB9C9RgOA.png" /><figcaption><strong>We could be in any of these n states at αₜ(i), and αₜ(i) will tell us the probability of being in ‘that’ state given all the observations that came before. Keep in mind, 1 ≤ j ≤ n as is 1≤ i ≤ n.</strong></figcaption></figure><p>Think of αₜ as messages being passed from one particular time step to the next time step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y7gBeKm-C7QUuFvWlb5KHA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wyRP9Qtar07xsbSB7DBZdg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hSPNVCGWvY2-Id8NMiQOXw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CCVxWLXYB6K7LdAwqzNqMA.png" /></figure><p>This is how you can visualize the message being passed forward.</p><p><strong>αₜ </strong>will basically thus tell us the most likely state at the t-th time step given that we have observed Y₁, Y₂,… Yₜ (as we get the probability of being in a particular state at the t-th time step, so the maximum of those will give us the most likely state given all the past observations)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zN-3khAc9uBeGRhuVRUcUg.png" /><figcaption><strong>ANOTHER WAY OF VISUALIZING THE NETWORK. THE HIDDEN VARIABLES TAKE ONLY 2 STATES (S₁ and S₂) , AS DO THE OBSERVED VARIABLES ( A and B)</strong></figcaption></figure><h4>The code implementation for the Forward Algorithm is as follows —</h4><pre>def forward_algorithm(self, observations):<br>        &quot;&quot;&quot;<br>        Implementing the Forward algorithm for continuous observations.<br>        <br>        Parameters:<br>        -----------<br>        observations : It is basically a list or numpy.ndarray<br>            Sequence of continuous observations<br>            <br>        Returns:<br>        --------<br>        float<br>            Probability of the observation sequence given the model<br>        numpy.ndarray<br>            α values (forward probabilities)<br>        &quot;&quot;&quot;<br>        T = len(observations)<br>        alpha = np.zeros((T, self.n_states))<br>       <br>        for j in range(self.n_states): # This is the initialization step<br>            alpha[0, j] = self.pi[j] * self.emission_prob(observations[0], j)<br>        <br>        for t in range(1, T): # This is the recursion step<br>            for j in range(self.n_states):<br>                alpha[t, j] = 0<br>                for i in range(self.n_states):<br>                    alpha[t, j] += alpha[t-1, i] * self.A[i, j]<br>                alpha[t, j] *= self.emission_prob(observations[t], j)<br>        <br>        likelihood = np.sum(alpha[T-1, :]) # Finally the terminating step<br>        <br>        return likelihood, alpha</pre><p>Let us now look at βₜ(i) i.e., the Backward Algorithm.</p><p>By definition, βₜ(i) = P(Yₜ₊₁, Yₜ₊₂, … Y_{T}| Xₜ = Sᵢ , <strong>λ</strong>). Or to simply put it, given that we are at Xₜ, what is the probability of seeing the future observations for all the different states Sᵢ we could be in, at Xₜ.</p><p>Similar to the <strong>α</strong>ₜ, we can also regard βₜ as some message passers, except that the directionality is opposite in this case. The intuition for the recursion step is as follows —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qpYnll9diAF4D2NNr4pSxg.png" /></figure><p>Thus, we recursively calculate the value of βₜ. The time complexity in this case also equals O(N²T).</p><p>To represent it in terms of the parameters, the base case becomes,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*6g9j-0Q3Bg9vIEywkwREjQ.png" /></figure><p>and the inductive step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*f1ZfMI1w1r5qdN1HrRrKtg.png" /></figure><p>Or, in other words, all the different future hidden states we could go in, given that we are at a particular state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*cC-DUrtrNWXXwVk6qdMvBw.png" /><figcaption><strong>We could be in any of these n states at βₜ(i), and βₜ(i) will tell us the probability of going in a particular state given the current one. Keep in mind, 1 ≤ j ≤ n as is 1≤ i ≤ n.</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u7iLA31QAP5BRa1Z3DFbqg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7APXaOSg0MogQ0nvwa3jDA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xuDsjGZulI4wLXdod42sPQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8qKrXYpJ5tYW0bjtr6kzLw.png" /></figure><p>This is how you can visualize the messages being passed backward.</p><p><strong>β</strong>ₜ tells us the most likely state at the t-th time step which generates the future observations Yₜ₊₁, Yₜ₊₂, … Y_{T} (as we get the probability of generating the future observations for every state<strong> Sᵢ</strong> that we could be in, at Xₜ.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tXN40FgwzOPGfZw0Apnmqw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*EXMRNdbH0fU9HDxlME3KSQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*X7k0b6HwkGkw3qI98alguw.png" /><figcaption><strong>STEP BY STEP WAY OF VISUALIZING THE MESSAGES BEING PASSED BY β. THE HIDDEN VARIABLES TAKE ONLY 2 STATES (S₁ and S₂) , AS DO THE OBSERVED VARIABLES ( B and C)</strong></figcaption></figure><h4>The code implementation for the Backward Algorithm is as follows —</h4><pre>def backward_algorithm(self, observations):<br>        &quot;&quot;&quot;<br>        Implementing the Backward algorithm for continuous observations.<br>        <br>        Parameters:<br>        -----------<br>        observations : list or numpy.ndarray<br>            Sequence of continuous observations<br>            <br>        Returns:<br>        --------<br>        numpy.ndarray<br>            β values (backward probabilities)<br>        &quot;&quot;&quot;<br>        T = len(observations)<br>        beta = np.zeros((T, self.n_states))<br>        <br>        beta[T-1, :] = 1 # The initialization step<br>        <br>        for t in range(T-2, -1, -1): # The recursion step<br>            for i in range(self.n_states):<br>                beta[t, i] = 0<br>                for j in range(self.n_states):<br>                    beta[t, i] += self.A[i, j] * self.emission_prob(observations[t+1], j) * beta[t+1, j]<br>        <br>        return beta</pre><p>You must be wondering, how do we combine these to get the P(X|Y) which was our main target? Or, in other words, what sequence of hidden states “<em>best</em>” explain the sequence of observations? Don’t worry buddy, I’ve got you covered.</p><p>One way to generate the hidden states that best describe the observations would be to choose states that are ‘<strong><em>individually most likely’</em></strong>.</p><p>So we define a variable, γₜ(i) = P(Xₜ =Sᵢ |Y, <strong>λ</strong>) [Probability that we are in state i at time step t, given all our observations Y (observations that have come before and observations that are going to come after, <strong>λ]</strong></p><p>Thus,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*-T6hti6hmLyl4pZgbfnn9g.png" /></figure><p>To simplify this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*WTpWilcQh-Injbu4IDOmrg.png" /><figcaption><strong>For every time step t, for every state Si that the hidden state X can take, we need to calculate this probability</strong></figcaption></figure><p>But what is the intuition behind this? Basically, γ utilizes the messages passed by both the <strong>α </strong>and <strong>β. </strong>α utilized the past messages and β observed the future messages, and combining both of them we get the messages passed to a particular hidden state given all the observations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G-GBDiLB_wZbkf4oCWiTRw.png" /></figure><p>Once we calculate <strong>γₜ(i) </strong>for every possible state <strong>Sᵢ</strong>, we can search over that particular state which generates the highest probability, and we can do that using —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/283/1*3810kx68EITJXvWyYn36DA.png" /></figure><p>where the argmax operator will give us the state that produces the highest probability for <strong>γₜ(i).</strong></p><p>In this way for every t, 1 ≤ t ≤ T, we have the hidden states that best describe the observations. Thus your intuition would say that combining these sequences would give us the entire hidden state sequence right? Well, sadly its not the case. While you see that we do have the best possible states that describe our observations, but no where did we account for the state transition probabilities between these hidden variables!</p><p>Let me give you an example. Suppose the transition probability between two states S₁ and S₂ is 0. And say at time step, Xₜ we find that <strong>γₜ </strong>is maximized for<strong> </strong>S₁. And, in the next time step Xₜ₊₁ we find that <strong>γₜ </strong>is maximized for<strong> </strong>S₂. When creating the sequence of hidden states, we would club together in a manner like this —</p><p>{…S₁,S₂…}1</p><p>But the state transition probability of going to S₂ from S₁ is 0. That is exactly where the “<strong>Viterbi Algorithm”</strong> comes in!</p><h3>The Decoding Problem: The Viterbi Algorithm</h3><p>Imagine you are analyzing a DNA sequence where the regions can be either coding (genes) or non-coding. These states are hidden, but we observe the actual nucleotides (A, C, G, T) (look up for these please, RNA have U, DNA lack them).</p><p>Let us say that:</p><ul><li>Our Hidden states: Coding (C), Non-coding (N),</li><li>The transition probabilities: P(C→C) = 0.9, P(C→N) = 0.1, P(N→C) = 0.2, P(N→N) = 0.8</li><li>The emission probabilities for coding regions: P(A|C) = 0.2, P(C|C) = 0.3, P(G|C) = 0.3, P(T|C) = 0.2 and the emission probabilities for Non-coding: P(A|N) = 0.3, P(C|N) = 0.2, P(G|N) = 0.2, P(T|N) = 0.3.</li></ul><p>Say we observe the sequence [A, C, G], what’s the most likely sequence of hidden states?</p><p>We could evaluate “<em>all possibilities</em>”, right? That is, calculate</p><ol><li>C→C→C: 0.6 × 0.9 × 0.2 × 0.9 × 0.3 × 0.9 × 0.3 = 0.026</li><li>C→C→N: 0.6×0.9×0.2×0.9×0.3×0.1×0.2 = 0.0006</li><li>C→N→C: 0.6×0.9×0.2×0.1×0.2×0.2×0.3 = 0.0004</li><li>C→N→N: 0.6×0.9×0.2×0.1×0.2×0.8×0.2 = 0.0015 … and so on.</li></ol><p>I’m sure you would agree with me when I say this is a highly impractical approach to find out all the path sequences possible and calculate the highest probability one. But, <em>how does the Viterbi Algorithm solve for this</em>?</p><p>Instead of looking at individual states that maximize the probability of the observations, we account for the “<strong>path sequence</strong>” that maximizes P(X|Y, λ).</p><p>Again, using the conditional probability to see,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/187/1*Whw_kw9z6U5WHZplPYsuJw.png" /></figure><p>Thus, our goal becomes to —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*vftr1i7Ln7b-nuBu0a_yBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*TANKOWnQsuaSnHlx3mh7hw.png" /></figure><p>Now one way would be to find out the probabilities for the entire length for every single state <strong>Sᵢ </strong>for every single<strong> </strong>Xₜ, and then finding out the path sequence with the highest probability. But that would be TOO computationally expensive!</p><p>The Viterbi Algorithm tracks the best path to each possible position at each steps using what it learnt from the previous steps. At each time step t, each state <strong>Sᵢ, </strong>compute the maximum probability of any path ending in state <strong>Sᵢ</strong> at time t that also matches the observation up to t.</p><p>We define variable δ as —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*YCZrW7hhbYEN0i0mEltf5g.png" /></figure><p>δₜ is basically maximizing the probability of a partial path up to time t, ending in state i. [Stand at a particular time step t, at a particular state <strong>Sᵢ </strong>and observe the state transition probability of transitioning to all other possible states in the next time step t+1 and maximize the probability of moving to the next time step.]</p><p>Mathematically, we initialize δ as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/167/1*fPOUBSNTQSdxXSX5kzKlvQ.png" /></figure><p>And the Inductive step is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*2Nnw2ZGOaFF-CYJywpdbCw.png" /></figure><p>subject to the conditions 2 ≤ t ≤ T ; 1 ≤ j ≤ N.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HyIFAZw32PVFMBPPY1x6Tw.png" /><figcaption><strong>A formal proof of the recursive step implemented</strong></figcaption></figure><p>Thus, for calculating δ’s at time t ( t&gt;1), we consider calculating the most probable path to the state X at the time t. This path to X will have to pass through one of the states S₁, S₂, … S_{N} at time (t-1), something like this —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*5IhUEK7qyukE322N9DOpng.png" /><figcaption><strong>If X is the most probable for the time step (t+1) then it will have to come from one of S1,…Sn</strong></figcaption></figure><p>The most probable path to X will thus be:</p><ul><li><strong>(sequence of hidden states</strong>)…S₁, X</li><li><strong>(sequence of hidden states</strong>)…S₂, X</li></ul><p>…</p><ul><li><strong>(sequence of hidden states</strong>)…Sₙ, X</li></ul><p>In other words, P(X at time t) = max. (i =S₁, S₂, .. Sₙ )P(Sᵢ at time (t-1)) *P(X|Sᵢ) * P(Y|X)</p><p>We also define, ψₜ(i) = state at (t-1) that achieves this maximum probability, which we use for backtracking to get to the most possible sequence of hidden states. This is because, we somehow need to remember the partial best paths through the trellis. To calculate δₜ(i) we only need δₜ₋₁(i). Having thus calculated this probability, it is possible to record which preceding state was the one to generate δ(i, t) — in what state the system must have been at (t-1) if it is to optimally arrive at state Sᵢ at time t.</p><p>Initialization:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/72/1*MAbZunp1JuNHkgfjK6sWGQ.png" /></figure><p>This is because, having observed nothing, there would be no possible sequence to backtrack.</p><p>The Inductive step is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*WZaCJY0uw1suYTE-lkP51A.png" /></figure><p>The termination steps for the Viterbi Algorithm become —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/178/1*6VgJ741ewhsX4btIjsFLuw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*ruuMbTjX22dmo_jDik6EkA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/116/1*wzMtctYFCXY_iDJSl33fxg.png" /></figure><h4>The code implementation for the Viterbi Algorithm is as follows —</h4><pre>def viterbi_algorithm(self, observations):<br>        &quot;&quot;&quot;<br>        Implementingthe Viterbi algorithm for continuous observations.<br>        <br>        Parameters used:<br>        -----------<br>        observations : list or numpy.ndarray<br>            Sequence of continuous observations<br>            <br>        Returns:<br>        --------<br>        list<br>            Most likely sequence of hidden states<br>        float<br>            Probability of the most likely sequence<br>        &quot;&quot;&quot;<br>        T = len(observations)<br>        delta = np.zeros((T, self.n_states))<br>        psi = np.zeros((T, self.n_states), dtype=int)<br>        <br>        for j in range(self.n_states): # Initializating the variables δ,ψ<br>            delta[0, j] = self.pi[j] * self.emission_prob(observations[0], j)<br>            psi[0, j] = 0<br>        <br>        for t in range(1, T): # Recursing through the states<br>            for j in range(self.n_states):<br>                probs = delta[t-1, :] * self.A[:, j] # Finding the maximum probability and corresponding state<br>                psi[t, j] = np.argmax(probs)<br>                delta[t, j] = np.max(probs) * self.emission_prob(observations[t], j)<br>        <br>        best_path_prob = np.max(delta[T-1, :]) # The Termination step<br>        best_path_end = np.argmax(delta[T-1, :])<br>        <br>        best_path = [best_path_end] # backtracking for the path!<br>        for t in range(T-1, 0, -1):<br>            best_path.insert(0, psi[t, best_path[0]])<br>        <br>        return best_path, best_path_prob</pre><p>So, we have learnt the hidden states that maximize our probability of seeing the sequences too! But, how do we learn the parameters? That is, how do we know what should “ideally” (well we can never achieve what is called an ideal value for the parameter as we shall see) be the values of the state transition matrix, the emission matrix, and the initialization which generated the data?</p><p>That is where the Baum-Welch Algorithm comes in!</p><h3>The learning problem: The Baum-Welch Algorithm</h3><p>Imagine you begin to believe that the market alternates between “Bull” and “Bear” regimes (after watching ‘The Wolf of the wall street’), but you don’t know:</p><ol><li>How frequently these regimes switch,</li><li>How each regime typically affects daily returns</li></ol><p>If all you have is historical daily returns (Up/Down/Flat etc.), how can you learn the hidden structure?</p><p>Let’s start with a guess:</p><ul><li>Our hidden states: Bull (B), Bear (R),</li><li>Our observations: Up (U), Flat (F), Down (D),</li><li>Initial guess at transition probabilities: P(B→B) = 0.8, P(B→R) = 0.2, P(R→B) = 0.3, P(R→R) = 0.7,</li><li>Initial guess at emission probabilities: Bull: P(U|B) = 0.6, P(F|B) = 0.3, P(D|B) = 0.1 — Bear: P(U|R) = 0.2, P(F|R) = 0.3, P(D|R) = 0.5,</li></ul><p>Given that our observed returns are [U, U, D, D, F, U], how do we refine our guesses?</p><p>Here’s the intuition to the Baum-Welch —</p><ol><li><strong>Given our current model</strong>: estimate how many times we likely visited each state(B/R) and made each transition(B to R and vice versa).</li><li><strong>Update our model</strong>: Adjust probabilities based on these estimated counts.</li><li><strong>Repeat</strong>: The model gradually improves with each iteration. For example, if you estimate you were in the Bull state 3 times and saw “Up” twice during those visits, we’d update P(U|B) to approximately 2/3.</li></ol><p>To formally define the problem, you want the parameters that generated the data given that you have ‘<em>just</em>’ the dataset of observations. But how would you leverage it for predictions if we do not know the parameters?</p><p>There is no such known way to analytically solve for the model which maximizes the probability of observed sequence. The calculation space for the same is very large, thus we utilize a Heuristic approach which produces a partial solution.</p><p>The initialization distribution (the parameters of the Dirichlet distribution π), the state transition probability matrix and the emission distribution matrix are all unknowns. We must set all these values to some initial values, which we can do in one of the following ways —</p><ul><li><strong>some form of uniform distribution</strong></li><li><strong>prior knowledge of the data</strong></li><li><strong>random guess (well we just start off on our road to achieve nirvana (not quite literally :D))</strong></li></ul><p>We define a new mathematical tool ξₜ(i) = P(Xₜ = Sᵢ, Xₜ₊₁ = Sⱼ | Y, λ)</p><p>which essentially captures at time t, the state we are at Sᵢ and the transition to Sⱼ at the next time step (t+1).</p><p>Mathematically,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*8d77IvVjL_CADNbHkSZTog.png" /></figure><p>A formal proof of the above can be given as shown —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ruJk5KiTiCrl1qUp-h-NSQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kr4Pu2qT3qv1t6aTZoCbQA.png" /><figcaption><strong>A visual of the thing actually going on in behind the scenes of the mathematics</strong></figcaption></figure><p>We might as well notice that, if we marginalize over the variable j for the time step (t+1) then the equation of the ξₜ(i, j) reduces to γₜ(i).</p><p>In other words,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/137/1*HLEFWc5W6sr7e2KLR2vABw.png" /></figure><p>Let us recall the definition of γₜ(i) which states that γₜ(i) = P(Xₜ =Sᵢ |Y, <strong>λ</strong>). Thus, if we sum over all t for γₜ(i), then we have the expected number of times a state Sᵢ is ever visited all throughout the length of observations of the Markov Chain.</p><p>Think of γₜ(i) as the best guess about the weather on a specific day t, based on the entire sequence of temperature readings you’ve collected. For example, if γ₃(Sunny) = 0.8 would mean that given all temperature readings across all days, you are 80% confident that the weather on day 3 was Sunny.</p><p>Now, when we sum γₜ(i) over all time steps t, we are essentially counting the number of times state Sᵢ occurs throughout the given observation sequence.</p><p>For example:</p><ul><li>If γ₁(Sunny) = 0.7, γ₂(Sunny) = 0.3, and γ₃(Sunny) = 0.9</li><li>Then ∑ₜ γₜ(Sunny) = 0.7 + 0.3 + 0.9 = 1.9</li></ul><p>The value 1.9 tells us that, given our temperature observations, we expect the weather to have been “Sunny” on approximately 1.9 days out of the 3 days observed.</p><p>Similarly, if we sum over all the t for ξₜ(i, j), we have the expected number of transitions from state Sᵢ to Sⱼ.</p><p>The Baum-Welch Algorithm is basically an EM algorithm (expectation maximization algorithm) which is iterative and converges to a local optimum. It refines the guesses by computing the expected counts of state at time step t and emissions from that state.</p><ul><li><strong>E Step</strong>: Given, the current Y, <strong>λ, </strong>we compute the estimated number of times we transition from<strong> </strong>Sᵢ to Sⱼ / emit symbol k given state Sᵢ.</li><li>M Step: Maximum likelihood by setting parameters to these expected counts, normalized appropriately.</li></ul><p>And we repeat this process until convergence.</p><p>So, now, we have an existing model, <strong>λ = [A, B, </strong>π], the observations Y, <strong>αₜ(i), β</strong>ₜ(i), γₜ(i), ξₜ(i, j).</p><p>How do we thus improve upon this model?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/97/1*3kMtqnwLROHDs9IUvNVHaw.png" /><figcaption><strong>The new set of parameters</strong></figcaption></figure><p>The values of the parameters are —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/73/1*rzKoraG6Z7U83Y8gpykCgA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/145/1*kM7UrzDJJf3oKSBt_naGaQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*2dro-EYLB52KBi_p2BPZRQ.png" /></figure><p>π* can be defined as the expected frequency in Sᵢ at t = 1,</p><p>aᵢⱼ* can be defined as the ratio of the expected number of transitions from state Sᵢ to Sⱼ to the expected number of transitions from state Sᵢ (quite intuitive, as aᵢⱼ represents the probability of the state transition from i to j. So, suppose out of 100 transitions from state Sᵢ, if 13 of them transition to j, then the value would be 0.13)</p><p>bᵢⱼ* can be defined as the ratio of the expected number of times state j comes up and the observed value is Vₖ to the expected number of transitions from state Sᵢ.</p><p>Thus, you start off with a value for λ and Y, produce αₜ(i), βₜ(i), γₜ(i), ξₜ(i, j) and then given the αₜ(i), βₜ(i), γₜ(i), ξₜ(i, j), update the values for λ and this process goes on until convergence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*rIyj5NT2RLzzW5KjxR7ksw.png" /><figcaption><strong>The process visually looks like this</strong></figcaption></figure><h4>The code implementation for the Baum-Welch Algorithm is as follows —</h4><pre>def baum_welch_algorithm(self, observations, max_iterations=100, tolerance=1e-6):<br>        &quot;&quot;&quot;<br>        Implementing the Baum-Welch algorithm for continuous observations.<br>        <br>        Parameters:<br>        -----------<br>        observations : list or numpy.ndarray<br>            Sequence of continuous observations (Y)<br>        max_iterations : int, optional<br>            Maximum number of iterations for a threshold <br>        tolerance : float, optional<br>            Convergence threshold<br>            <br>        Returns:<br>        --------<br>        float<br>            Log likelihood of the final model<br>        &quot;&quot;&quot;<br>        T = len(observations)<br>        old_likelihood = -float(&#39;inf&#39;)<br>        <br>        for iteration in range(max_iterations):<br>            likelihood, alpha = self.forward_algorithm(observations) # E-step: Computing the forward and backward probabilities<br>            beta = self.backward_algorithm(observations)<br>           <br>            gamma = np.zeros((T, self.n_states))# Initializing the values of gamma and xi<br>            xi = np.zeros((T-1, self.n_states, self.n_states))<br>            <br>           for t in range(T): # Calculating the value of gamma (probability of being in state i at time t)<br>                denominator = np.sum(alpha[t, :] * beta[t, :])<br>                for i in range(self.n_states):<br>                    gamma[t, i] = alpha[t, i] * beta[t, i] / denominator<br>            <br>            for t in range(T-1): # Calculating the values of xi (probability of being in state i at t and state j at t+1)<br>                denominator = 0<br>                for i in range(self.n_states):<br>                    for j in range(self.n_states):<br>                        xi[t, i, j] = alpha[t, i] * self.A[i, j] * \<br>                                     self.emission_prob(observations[t+1], j) * beta[t+1, j]<br>                        denominator += xi[t, i, j]<br>                <br>                xi[t, :, :] /= denominator<br>            <br>            # M-step: Updating the parameters<br>            # Updating the initial state probabilities<br>            self.pi = gamma[0, :]<br>            <br>            for i in range(self.n_states): # Updating the transition probabilities<br>                denominator = np.sum(gamma[:-1, i])<br>                for j in range(self.n_states):<br>                    self.A[i, j] = np.sum(xi[:, i, j]) / denominator<br><br>            for j in range(self.n_states): # Updating the emission parameters (mean and variance)<br>                # Update mean<br>                numerator = np.sum(gamma[:, j] * observations)<br>                denominator = np.sum(gamma[:, j])<br>                self.means[j] = numerator / denominator<br>                <br>                numerator = np.sum(gamma[:, j] * (observations - self.means[j])**2) # Updating the variance<br>                self.variances[j] = numerator / denominator<br>            <br>            if abs(likelihood - old_likelihood) &lt; tolerance: # Checking for convergence<br>                break<br>                <br>            old_likelihood = likelihood<br>        <br>        return np.log(likelihood) if likelihood &gt; 0 else -float(&#39;inf&#39;)</pre><p>For the codes above, we had prepared synthetic data and the code for that is as follows —</p><pre>def prepare_synthetic_data(sequence_length=100):<br>    &quot;&quot;&quot;<br>    Creating synthetic weather data with continuous temperature observations.<br>    <br>    Parameters:<br>    -----------<br>    sequence_length : int<br>        Length of the sequence to generate<br>        <br>    Returns:<br>    --------<br>    numpy.ndarray<br>        Sequence of continuous observations (temperature)<br>    list<br>        True hidden states (weather conditions)<br>    dict<br>        Mapping of numeric states to weather conditions<br>    &quot;&quot;&quot;<br>    # Defining the true model parameters<br>    n_states = 3  # Sunny (0), Cloudy (1), Rainy (2)<br>    <br>    # The true transition probabilities<br>    A_true = np.array([<br>        [0.7, 0.2, 0.1],  # Sunny -&gt; Sunny/Cloudy/Rainy<br>        [0.3, 0.5, 0.2],  # Cloudy -&gt; Sunny/Cloudy/Rainy<br>        [0.2, 0.3, 0.5]   # Rainy -&gt; Sunny/Cloudy/Rainy<br>    ])<br>    <br>    # The true emission parameters (mean and variance for each of the states)<br>    means_true = np.array([30.0, 22.0, 15.0])  # Mean temperatures for Sunny, Cloudy, Rainy<br>    variances_true = np.array([4.0, 3.0, 2.0])  # Variances for Sunny, Cloudy, Rainy<br>    <br>    # Initial state distribution<br>    pi_true = np.array([0.4, 0.4, 0.2])<br>    <br>    states = []# Generating the hidden state sequence (hre, weather)<br>    current_state = np.random.choice(n_states, p=pi_true)<br>    states.append(current_state)<br>    <br>    for t in range(1, sequence_length):<br>        current_state = np.random.choice(n_states, p=A_true[current_state])<br>        states.append(current_state)<br>    <br>    observations = []# Generating the observations (here, temperature)<br>    for state in states:<br>        observation = np.random.normal(means_true[state], np.sqrt(variances_true[state])) # Drawing from Gaussian distribution with state-specific mean and variance<br>        observations.append(observation)<br>    <br>    # Defining the mapping for interpretation<br>    state_mapping = {0: &quot;Sunny&quot;, 1: &quot;Cloudy&quot;, 2: &quot;Rainy&quot;}<br>    <br>    return np.array(observations), states, state_mapping</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vfuo_NlHcvlc44jSHB_00w.png" /><figcaption><strong>This is how the data looked like upon prediction</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*nf_VNy7YIi_mtQMDO1RmPw.png" /><figcaption><strong>You can see how the weather state transition probabilities changed over the course (eg. from 0.7 for sunny to sunny it reduced to 0.64)</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*iK_XDufLUdbzlo843Bv_YA.png" /><figcaption><strong>The values for the mean and the variances also changed over the course of the data. We believed the data to have originated from gaussian processes with mean and variances for each state.</strong></figcaption></figure><h3><strong>Limitations and Challenges:</strong></h3><h4>Computational Complexity Challenges</h4><ol><li>The Forward-Backward, Viterbi and the BW algorithm all have a computational complexity of O(TN²). While it is obviously a big step down from the O(T*N^T) yet it is quite computationally expensive for large datasets or real-time applications.</li><li>Parameter Estimation: HMMs require estimating a large number of parameters. Even a 4 state HMM with 5 continuous distributions as channels would need 50 parameters to be evaluated. Too big a number, right?</li><li>Due to the large number of parameters, HMMs need extensive training data, which can be difficult to obtain at times.</li></ol><h4>When HMMs Might Not Be Appropriate</h4><ol><li>HMMs assume a fixed number of hidden states, thus not able to their ability to model systems that evolve with time. We assumed the parameters to be time dependent, it always need not happen this way, in fact rarely are the parameters time dependent.</li><li>The Markovian assumption (that the future state depends only on the current state) doesn’t hold in many real-world scenarios like stock market predictions where multiple past events influence the overall trends.</li><li>When the data is limited, HMMs fail to generalize well, leading to inaccurate predictions in domains like medical diagnosis of rare diseases.</li><li>For applications that require immediate responses, the computational complexity of HMMs can be prohibitive without parallelization.</li><li>Traditional HMMs can struggle with continuous observation spaces without appropriate modifications.</li></ol><h4>Conclusion</h4><p>This brings us to the end of the implementation of the HMM from Scratch! Oooof! Long read, right? A lot of mathematical formulas there. We have finally developed the tools needed to catch our elusive thief xD.</p><p>Through the FB algorithm, we learnt to calculate his probability of being in Milan based on the cues of Pizza and AC Milan. With the Viterbi algorithm, we’ve constructed his most likely route over the past month or so, and through the BW algorithm, we’ve refined our understanding of his movement patterns and the cues he leaves behind.</p><p>So, my detective, the next time you receive a mysterious letter from a thief with such subtle clues, do not forget the power of HMM! :D</p><p>(Refer to my Github repository where I implemented this from scratch, for a better understanding. — <a href="https://github.com/YashDaga874/FROM_SCRATCH_SERIES">https://github.com/YashDaga874/FROM_SCRATCH_SERIES</a>. It also contains visualizations so you can help yourself with them!)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2c725296896" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Anatomy of a Topic Model: Implementing Latent Dirichlet Allocation from First Principles]]></title>
            <link>https://medium.com/@daga.yash/the-anatomy-of-a-topic-model-implementing-latent-dirichlet-allocation-from-first-principles-f262fa72779a?source=rss-ed1ff4a9d6bd------2</link>
            <guid isPermaLink="false">https://medium.com/p/f262fa72779a</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[topic-modeling]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Yash]]></dc:creator>
            <pubDate>Wed, 05 Mar 2025 16:35:16 GMT</pubDate>
            <atom:updated>2025-03-19T10:52:54.487Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Ground Up series(part 1): The Anatomy of a Topic Model (LDA)</h3><p>Hey there! Imagine you are walking into a library containing thousands of books with no organization system. There are no genres, no categories, no ways whatsoever to know what any book is about without reading it cover to cover. Traumatizing right? Now imagine you have a magical lens that somehow reveals the underlying themes behind all these books, showing you which ones discuss politics, which ones discuss sports, and which ones discuss science — all without anyone having manually labeled them.</p><p>Essentially, LDA is just basically that magical lens of yours. It’s like the X-ray for your documents, revealing their hidden thematic structures.</p><p>Latent Dirichlet Allocation(LDA) is basically a generative probabilistic model that is used in topic modeling. Quite a few terms, right? Let me take you through them one by one.</p><h3><em>INTUITION ON TOPIC MODEL, GENERATIVE MODEL AND PROBABILISTIC GRAPHICAL MODEL</em></h3><p>At its heart, t<em>opic model</em><strong> </strong>is basically a statistical approach in abstracting ‘topics’ from a collection of documents. For example, an article repeatedly using words like ‘bat’, ‘wicket’, ‘goal’, and ‘stadium’ likely discusses sports, whereas one containing ‘planet’, ‘orbit’ and ‘telescope’ probably focuses on science.</p><p>And what is a <em>generative model</em>? It is one that explains how the data might have been generated in the first place. Think of it like this — you are making a chocolate cake. The generative model would attempt to describe the ingredients and the steps that went behind making the cake.</p><p>A <em>Probabilistic Graphical Model</em> formally presents complex probability distributions through graphs where each node represents a random variable and the edges encode dependence relationships between these variables. PGMs leverage graph theory and factorize the join probability distributions into smaller subsets of variable functions. In case of Directed Graphical Models (DGMs), we represent the joint distribution in terms of conditional independence between variables which are shown via edges. LDA is one such model. Let’s see how we represent the joint distribution in case of DGMs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*0DdHOOW1XveiL8-isL_a-Q.png" /><figcaption><strong>Given the above graph structure, factorization of the joint distribution in case of DGMs is done as follows -</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*iTcFqbSp37B4wzfnxiJjZQ.png" /></figure><p>where, X{i} represents the node,</p><p>pa(X{i}) represents the parent vertex for that particular node. For example,</p><p>pa(A) = {φ}, pa(B) = {A}, pa(C) = {A,B} since it’s value depends on both A, B.</p><p>This is how we represent the joint pdf in DGMs. LDA is just basically a DGM model. We will later see how we mathematically formulate our requirement.</p><p>Not sure how we connect all of this into LDA? Hang on buddy, we are almost there!</p><h4>Connecting the dots —</h4><p>For us, humans, we do develop the knowledge about the world via various topics. In addition to that we are good at adjusting the context on the fly, i.e., we know that the same word carries a completely different meaning in a completely different context. ‘Red wine’ and ‘red hair’ might indicate the same color but in meaning, are two very different topics we are talking about. In short, we are masters at understanding ‘topic’, ‘word’ and the ‘context’. But how do we put all of this or at least some of it into a machine, so that we can automate finding similar magazines, and in a way such that recommendations almost feel human-like? We try and formulate all of this into a mathematical equation that encapsulates ‘topic’, ‘word’ and the right window of ‘context’.</p><p><em>But how does LDA do it? Let us think from a generative perspective.</em></p><p>First, imagine we have a set of topics (say K topics, here for the sake of explanation let us take K=3) and each topic has its own distribution over words present in the vocabulary (a Dirichlet prior distribution).</p><ul><li>The topic “Science” might give high probability to words like “planet” (0.05), “experiment” (0.04), “hypothesis” (0.03), etc.</li><li>The topic “Sports” might give high probability to words like “ball” (0.06), “team” (0.05), “score” (0.04), etc.</li><li>The topic “Politics” might give high probability to words like “government”(0.05), “law” (0.03) etc. and so on.</li></ul><p>Suppose we want to generate a collection or mixture of topics. For example, the first document we want to generate should be [0.7 Science, 0.2 Sports, 0.1 Politics]. The second document we want to generate should be [0.8 Politics, 0.15 Sports, 0.05 Science]. These numbers represent a topic’s proportion in a particular document (a Dirichlet distribution).</p><p>Now that the topic distribution is selected, we sample from that distribution N number of times (N representing the number of words we want to generate in that document). Once drawn the topics, corresponding to each topic, a word is randomly selected from that topic’s word distribution.</p><p>Let me take you through an example. Say we take, N = 8, and we draw 5 words from topic ‘Science’ , 2 from ‘Sports’ and 1 from ‘Politics’. The sequence of topics sampled are as follows —{Sports, Science, Science, Science, Science, Politics, Science, Sports}.</p><p>Corresponding to each sample drawn, we draw a word accordingly from that topic’s word distribution. So the words drawn corresponding to the above sampled topic in sequence are — {Ball, Planet, Planet, Government, Galaxy, Government, Galaxy and Ball}.</p><p>Thus, these sequence of words form our document generated. So basically its a Bag of Words (BOW) model, where there is no link between the words generated i.e., they are not dependent on each other as in say, a n-gram model. But why is it so? And how do we ‘<em>label</em>’ topics?</p><h3>PLATE NOTATION OF LDA MODEL</h3><p>Have a look at the plate notation of the model —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*nRvpjMvRPdSnQOGod50SFQ.jpeg" /><figcaption><strong>Plate notation for a LDA model</strong></figcaption></figure><p>Okay, but what does a plate notation denote?</p><p>Basically, its a condensed form of writing the graphical model.</p><p>Here in the case of LDA, it denotes —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*59xR7c8K2eoeWeCi4jyeoQ.png" /><figcaption><strong>The joint pdf in a LDA model</strong></figcaption></figure><p>where, <strong>α = prior Dirichlet</strong> for the document-topic mixtures (Θ). What does it tell us? It is our prior belief about how topics are distributed in a document. A higher value of α means that a particular document contains more topics evenly (a document becomes a loose collection over more topics) whereas a lesser value of α is indicative that the documents will have more tendency to be concentrated over particular topics. For example, with α = 0.1, documents might be 90% about one topic and have minimal contributions from others.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ljs5Za5Hvaf6Z7gPRekvIw.png" /><figcaption><strong>Look how α affects the document-topic mixture, dots being closer to a particular corner means that the document is concentrated over that topic.</strong></figcaption></figure><p><strong>β = prior Dirichlet</strong> for the topic-word distribution (φ). It is our prior belief about how words are distributed over a topic. A higher value of β would mean that the probability mass is more evenly spread over the vocabulary of words. Thus, we won’t have differentiative words between the topics. A lower β though means a more concentrated and a smaller set of words encapsulated by a particular topic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*ebVcH2NQERhxdChywSLRkg.png" /><figcaption><strong>The β prior distribution. Closer the dot to a particular vertex, higher is its probability.(Given only these 4 words, 3 topics). See how ‘Sports’ is almost exclusive to ‘ball’, meanwhile ‘Science’ encompasses ‘Planet’ and ‘Galaxy’ with good probability. (Generated for illustration purposes only)</strong></figcaption></figure><p>These two are the hyperparameters for our model.</p><p><strong>Θ{d} ~ Dirichlet(α)</strong>.For every document d, Θ{d} is the probability distribution over topics. Its a vector of length K (=number of topics), where every the ith entry denotes the proportion of ith topic in the dth document. If for a particular document we have Θ{d} ~ [0.7 Science, 0.2 Sports, 0.1 Politics]. It means the proportion of words in the document coming from the topic Science is 0.7, proportion of words coming from Sports is 0.2 and so on.</p><p><strong>Z{d,n} ~ Categorical(Θ{d})</strong> (think about it as the topic for the nth word in the dth document). Given the distribution of Θ{d}, we have a single draw from the multinomial distribution. Say, the sample draw turns out to be “Science” given our Θ{d}.</p><p><strong>ϕ{k}​∼Dirichlet(β)</strong>. For every topic, we have a probability distribution over the words in the vocabulary. Words like “ball”, ”post” etc. will have higher probability mass in the topic “Sports” as we discussed earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WiaP284HnhH7w3yg7KITEg.png" /><figcaption><strong>Word distribution over topics (Just a small visualization)</strong></figcaption></figure><p>When writing out the probability density function for the Dirichlet distribution, the mathematical expression becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*R9_ss5zBjgLIGersOW_Y1w.png" /><figcaption><strong>The pdf of the Dirichlet distribution</strong></figcaption></figure><p>Here, V denotes the vocabulary size, ϕ{k,v} is the probability of word v in topic k, β{v} denotes the dirichlet parameter.</p><p><strong>W{d,n}∼Multinomial(ϕ{z{d,n}}​​).</strong> Now that we have the topic for the word selected, we sample a word from that particular topic. Like for example, if Z{d,n} = “Sports” then a word sampled from that topic could be W{d,n} = “Ball”.</p><p>Thus, in this way we generate the document.</p><p>This is fine but you must be wondering, <em>how do we train this model? How do we maximize our probability of generating the same document that we provide? And what exactly is the Dirichlet distribution?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9aUnLZzbjhkQetmLkSkV_g.png" /><figcaption><strong>This is how we have different topics in a document. (Source : IBM)</strong></figcaption></figure><h3>The Magic Behind the Model: The Dirichlet Distribution</h3><p>So in the previous sections, I had explained how the parameters Θ{d} and ϕ{k} come from two Dirichlet distributions with parameters α and β respectively. But what is it?</p><p>Imagine you’re a chef creating a fruit smoothie with three ingredients — strawberries, bananas, and mangoes. The proportions of all ingredients must sum to 1. So you could make:</p><ul><li>A pure strawberry smoothie (100% strawberries, 0% bananas, 0% mangoes)</li><li>A balanced blend (33% strawberries, 33% bananas, 33% mangoes)</li><li>Any other combination where the percentages add up to 100%</li></ul><p>Now, we can visualize all possible smoothies as points on a triangle:</p><ul><li>Each corner represents a pure, single-fruit smoothie</li><li>The middle represents an equal mix of all three fruits</li><li>All other points represent different combinations of the three fruits</li></ul><p>The Dirichlet distribution gives us a way to model the probability o</p><p>f different recipes. Its parameter α controls what kinds of mixtures are likely:</p><ul><li>With α &lt; 1 (say α = 0.1): The distribution favors ‘purist’ recipes that use primarily one fruit, with small amounts of others. Most probability mass is near the corners.</li><li>With α = 1: All possible recipes are equally likely. This is a uniform distribution over the triangle.</li><li>With α &gt; 1 (say α = 10): The distribution favors balanced recipes with more equal proportions of each fruit. Most probability mass is concentrated near the center.</li></ul><p>Thus drawing parallels with our model:</p><ol><li>The document-topic mixtures: The ‘recipe’ for how topics are mixed in each document</li><li>The topic-word distributions: The ‘recipe’ for how words are distributed within each topic</li></ol><p>Mathematically, the Dirichlet distribution is a family of continous multivariate probability distributions. For a K-dimensional Dirichlet distribution with parameter vector α = (α1,α2,..αk), the pdf is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*MjaN8wloYs9ryPn5iWGXCA.png" /></figure><p>where, Θ = (Θ1,Θ2,…Θk) is a probability vector (Θi ≥ 0 and ∑Θi = 1),</p><p>Γ is the gamma fn. and αi = concentration parameters.</p><p>The product term, is the key part which shapes our distribution as in when αi &lt; 1, values of Θi near 0 or 1 are more likely, when αi = 1, all valid Θ values are equally likely and when αi &gt; 1, values of Θi tend toward the expected value E[Θi] = αi/∑αi. In LDA, typically we use a symmetric Dirichlet distribution where all αi have same value, simplifying our calculation.</p><h3><strong>Inference and Parameter Estimation in LDA</strong></h3><p>The actual use case of a LDA model lies not in generating documents but in clustering the documents into topics. This is because of how the words are generated, with no dependence on the previous word (refer to the plate notation).</p><p>So, given the documents (W{d,n}), our main goal is to infer the hidden parameters Θ{d}, Z{d,n}, ϕ{k}​ (“<strong>latent variables”</strong> as they are called) that maximize the likelihood of the event happening. Thus, we observe just the words, and our goal is to infer the topics, topic distributions.</p><p>How do we start? We assign a topic to each of the words, for every document in our corpus. Our goal is —</p><ol><li>documents to be as monochromatic as possible.</li><li>words to be as monochromatic as possible.</li></ol><p>This is because, chances of a particular document discussing a range of topics is very less. Similarly, chances of one particular word being used in different topics is also less (well the proportion of words that are used in many different topics is less, right?)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*-Exq3aEyO0tqLHK71RPIVw.png" /><figcaption><strong>Assigning of topics to every ball, keeping the above 2 constraints in mind</strong></figcaption></figure><p>In the above example, we try to estimate the best guess for labelling the topic to ‘every word’ such that —</p><ol><li>documents are as monochromatic as possible.</li><li>words are as monochromatic as possible.</li></ol><p>Have a look at the illustration given. We multiply the two factors. Clearly, we see the area under curve for the first case is the most ( (3+α)(3+β) ). Hence, the topic 2 is assigned to the first word ‘ball’ in the document 1. In this way, we do it for every word.</p><p>Now, question would arise why do we add up α, β. Its because, say for example, there’s no ‘ball’ that’s labelled as topic 2 in doc 1, but all the rest of ‘ball’ in the rest of the docs are labelled as topic 2. So, in this case we see that multiplying by 0 would result in the area under curve being equal to 0. Ideally, blue should be labelled as topic 2, right? Hence, we add the parameters α, β (the dirichlet parameters defined).</p><p>This way we get the best possible fit after iterating for a few rounds such that our requirements are met.</p><p>Now that we have laid the foundations for the inference, let us dive into the mathematics.</p><p>Our goal is to learn the distribution of the latent variables given the hyperparameters and the words observed in a document. In other words we want to learn,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*6XhDPeco515SH374hsNchQ.png" /></figure><p>Exact inferencing using techniques like Variable Elimination is not possible because of the denominator (it is intractable to compute). We thus use an approximate inferencing technique called the Gibbs Sampling technique to learn the parameters. (The original paper by David M. Blei, Andrew Y. Ng uses Variational Inference as their inferencing technique.)</p><h3>Intuition behind Gibbs Sampling</h3><p>It is a ‘<strong><em>Markov Chain Monte Carlo’ </em></strong>technique for finding out the probability distributions of certain variables conditioned on other variables. The main idea remains that when sampling from a joint distribution P(X) = P(X1,…Xm) is difficult but sampling Xi such that P(Xi|C) is easier (where C = {Xj such that Xi ≠ Xj})</p><p>Now, we are interested in estimating Θ{d}, Z{d,n}, ϕ{k}​. We see that Z{d,n} is a sufficient statistic for both Θ{d} and ϕ{k}, and once we estimate Z{d,n}, we can estimate both the other latent variables.</p><p>But question again arises, why?</p><p>One way to think is — suppose you know both Z{d,n} and W{d,n} i.e., for every word token in every document in your corpus, you know which topic it is assigned to.</p><p>Like for example, if you know that the words in a document are — {Ball, Planet, Post, Country, Atom} and that the topics assigned to them are — {Sports, Science, Sports, Politics, Science}, then can we not find out Θ{d} i.e., the topic distribution in a particular document? Ofcourse, it will just be the proportion of topics assigned to topic 1, topic 2,..topic K. Thus, Θ{d} in this case = [0.4, 0.2, 0.4] where the first element tells the proportion of words having topic 1 in that document, second element tells proportion of words having topic 2 and so on..In our case, we took 5 words and 3 topics and had topics assigned to each of the 5 words. In other words,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/196/1*0bwzXNzlX8osOvm5HWyqcQ.png" /></figure><p>Here, N{di} represents number of words that fall under that topic, N{d} represents total number of words.</p><p>Similarly, across all documents, we can find out the number of occurences for every word for every topic. In this way, we can estimate the ϕ{k}.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*uOUIyqYBlgLBXTEWeAMUNA.png" /></figure><p>Here, M{k1} represents the number of occurrences of the first word in the vocabulary that has been assigned the topic ϕ{k}. Like for example, how many times has ‘ball’ been labelled under topic ‘Sports’ etc. This goes for the entire length of vocabulary V. And, M{k} represents the total number of words that have been assigned the topic M{k}.</p><p>Thus, if we just inference on Z, our job is done!</p><p>The algorithm that Gibbs sampling implies is as follows —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*gJ7jeWRAPTRLIbMRZvOpSQ.png" /></figure><p>But, why do we just sample on Z and not on Θ{d} and ϕ{k} too? Because, drawing samples from Θ{d} and ϕ{k} is difficult as it is a continous distribution over a range. Drawing samples over Z is relatively simple since it is discrete (takes just one of the K topic values). This method is also known as<strong> “Collapsed Gibbs Sampling”.</strong></p><p>Thus, more formally, we are interested in computing the following posterior up to a constant :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/226/1*WxPNqpk7ZS98b6iwknQc8Q.png" /></figure><p>where, Z{-i} means all topic allocations except for Z{i} (thats how it is a Gibbs sampler). To begin, the rules of conditional probability tell us that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*yLc8FYXwrE8l1ikDxCdAag.png" /></figure><p>Then we have,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*GlfLrZfQsRQOly-fu8Amtg.png" /></figure><p>We marginalize over Θ, Φ because of the above reason mentioned. Following our definition of LDA model, we expand the above equation to get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*4wxhEWAJ37Unk9v110_MOA.png" /></figure><p>We group the terms that have dependent variables:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*NWj75FNFM3gaVuq9iMDzeg.png" /></figure><p>Both the terms are multinomials with Dirichlet priors. Because the Dirichlet distribution is conjugate to the multinomial distribution, multiplying the two results in a Dirichlet distribution with an adjusted parameter. The two terms reduce to :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*V8lnGWLlYnuKeUW6x5MJkQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*tQOtmPAvOz1_ddm5kHIrFQ.png" /></figure><p>Combining the above two equations we get,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*d1On3YAsvLtqa9ngKxZRyA.png" /></figure><p>Finally, we have,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mdhMHTL5Fk5rFpYv2UePsA.png" /></figure><p>where, n{d,k} = number of words assigned to particular topic k in document d,</p><p>n{k,w} = number of times a word w is assigned to topic k,</p><p>z = current topic assignment for each of N words in the corpus.</p><h3>Implementation of Gibbs Sampling</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*Rw8htoMf2EnkWaMAPE5l_w.png" /></figure><p>So, we need to setup the requisite count variable, randomly initialize them, run a loop over the desired number of iterations where on each loop, “a topic is sampled for each word instance in the corpus.” Following Gibbs iterations, calculate Θ{d} and ϕ{k}.</p><pre># Dirichlet hyperparameters<br>ALPHA = 0.1  # Document-topic Dirichlet prior<br>BETA = 0.1   # Topic-word Dirichlet prior<br>NUM_TOPICS = 20<br>ITERATIONS = 200<br>sp = spacy.load(&quot;en_core_web_sm&quot;)</pre><p>We initialize the hyperparameters as α = 0.1 (documents are concentrated over a small range of topics), β (small value again, so that the words across topics are not really common) and the number of iterations for Gibbs Sampling = 200 (took up a lot of time to compute on my dataset xD).</p><pre>def generate_frequencies(data, max_docs=10000):<br>    #Generating word frequencies from documents<br>    freqs = Counter()<br>    all_stopwords = sp.Defaults.stop_words<br>    nr_tokens = 0<br><br>    for doc in data[:max_docs]:<br>        if isinstance(doc, str):<br>            tokens = sp.tokenizer(doc)<br>            for token in tokens:<br>                token_text = token.text.lower()<br>                if token_text not in all_stopwords and token.is_alpha and len(token_text) &gt; 2:<br>                    nr_tokens += 1<br>                    freqs[token_text] += 1<br>    <br>    print(f&quot;Total tokens before filtering: {nr_tokens}&quot;)<br>    print(f&quot;Unique words before filtering: {len(freqs)}&quot;)<br>    return freqs</pre><p>Given code snippet processes the documents to create word frequency counts, handling stop words and filtering.</p><pre>def get_vocab(freqs, freq_threshold=3):<br>    #Building vocabulary from word frequencies<br>    vocab = {}<br>    vocab_idx_str = {}<br>    vocab_idx = 0<br><br>    for word in freqs:<br>        if freqs[word] &gt;= freq_threshold:<br>            vocab[word] = vocab_idx<br>            vocab_idx_str[vocab_idx] = word<br>            vocab_idx += 1<br>    <br>    print(f&quot;Vocabulary size after filtering: {len(vocab)}&quot;)<br>    return vocab, vocab_idx_str</pre><p>The above code is to build the vocabulary mapping between words and indices, which is essential for the numerical processing in the algorithm.</p><pre>def LDA_collapsed_Gibbs(corpus, vocab_size, num_topics=NUM_TOPICS, num_iter=ITERATIONS) #Implementing LDA using collapsed Gibbs sampling<br>    # Initializing counts and Z<br>    Z = []<br>    num_docs = len(corpus)<br>    <br>    for doc_idx, doc in enumerate(corpus):<br>        Zd = np.random.randint(low=0, high=num_topics, size=len(doc))<br>        Z.append(Zd)<br>    <br>    ndk = np.zeros((num_docs, num_topics))  # document-topic counts<br>    for d in range(num_docs):<br>        for k in range(num_topics):<br>            ndk[d, k] = np.sum(Z[d] == k)<br>    <br>    nkw = np.zeros((num_topics, vocab_size))  # topic-word counts<br>    for doc_idx, doc in enumerate(corpus):<br>        for i, word in enumerate(doc):<br>            topic = Z[doc_idx][i]<br>            nkw[topic, word] += 1<br>    <br>    nk = np.sum(nkw, axis=1)  # topic counts<br>    topic_list = list(range(num_topics))<br>   <br>    print(&quot;Starting Gibbs sampling iterations...&quot;) # Gibbs sampling iterations<br>    for iteration in tqdm(range(num_iter)):<br>        for doc_idx, doc in enumerate(corpus):<br>            for i in range(len(doc)):<br>                word = doc[i]<br>                topic = Z[doc_idx][i]<br>                <br>                # Removing current assignment<br>                ndk[doc_idx, topic] -= 1<br>                nkw[topic, word] -= 1<br>                nk[topic] -= 1<br>                <br>                # Sampling a new topic<br>                p_z = (ndk[doc_idx, :] + ALPHA) * (nkw[:, word] + BETA) / (nk[:] + BETA * vocab_size)<br>                <br>                # Normalizing the probabilities<br>                p_z = p_z / np.sum(p_z)<br>                <br>                topic = random.choices(topic_list, weights=p_z, k=1)[0]<br>                <br>                # Updating counts with new assignment<br>                Z[doc_idx][i] = topic<br>                ndk[doc_idx, topic] += 1<br>                nkw[topic, word] += 1<br>                nk[topic] += 1<br>        <br>        if (iteration + 1) % 10 == 0:<br>            print(f&quot;Completed iteration {iteration + 1}/{num_iter}&quot;)<br>    <br>    return Z, ndk, nkw, nk</pre><p>The above code is heart of the implementation of LDA with Gibbs Sampling, according to the algorithm shown above. These three code snippets effectively capture the core algorithm.</p><p>Finally, to wrap up,</p><pre># Calculating phi (topic-word distribution)<br>phi = (nkw + beta) / (nk.reshape(NUM_TOPICS, 1) + beta * vocab_size)<br><br># Calculating theta (document-topic distribution)<br>theta = (ndk + alpha) / (np.sum(ndk, axis=1).reshape(-1, 1) + alpha * NUM_TOPICS)</pre><p>Here, we have the calculation for estimation of Θ, Φ.</p><h3>PRACTICAL CONSIDERATIONS</h3><h4>1. Choosing K (Number of topics)</h4><p>Selecting the optimal number of topics is more art than science. Too few topics will lead to overly broad, mixed topics where as too many can lead to fragmented, overlapping topics. Some considerations you can take — Try different K values, and choose the one that minimizes perplexity, but again lower perplexity doesn’t always mean more interpretable topics. Another approach could be making use of domain knowledge of the corpus.</p><h4>2. Setting Good values for α and β</h4><p>While these hyperparameters can significantly impact your results, reasonable defaults exist:</p><ul><li><strong>α (document-topic prior)</strong>: Lower values (0.01–0.1) are typically better for most applications, encouraging documents to focus on fewer topics. For extremely short documents, slightly higher values (0.5–1.0) might work better.</li><li><strong>β (topic-word prior)</strong>: Values between 0.01–0.1 work well for most applications. Lower values produce topics with fewer, more distinctive words.</li><li><strong>Asymmetric priors</strong>: For advanced applications, consider asymmetric priors where some topics are a priori more likely than others.</li></ul><p>Try a few different values and examine the resulting topics for coherence.</p><h4>3. Burn in-period</h4><p>Discard the first few hundred samples. This is because the randomness remains when we initialize the sample value for the first time (first step of Gibbs sampling). And this randomness is carried over to all the Z’s. So it is a healthy habit to discard them as the chain reaches its stationary distribution.</p><h4>4. Number of iterations</h4><p>How to know when to stop Gibbs sampling?</p><p>a. Fixed iterations — In the dataset I worked on, I just took about 200 iterations, which seemed to work just as fine, but a good practice could be taking around 1000–2000 iterations on small to medium corpus.</p><p>b. Log-likelihood stability — Monitor the change in log-likelihood between iterations, plateaus indicate that model has likely converged.</p><p>c. Sample lag — To reduce autocorrelation (since we can say that the sample 2 of all the Z’s is somewhat dependent on the sample 1), a good practice could be considering only the nth sample (eg. every 10th or 50th iteration) for the final topic estimates.</p><h3>Conclusion</h3><p>Woah, that was one long read, right? It takes a while for this to settle down as its too much information in one go to take. But do you remember our library metaphor from the beginning? We started off with thousands of unorganized books and sought a magical lens to reveal their underlying themes. Through LDA, we’ve built exactly just that, a computational approach to discover hidden topics within collections of documents.</p><p>So, the next time you encounter a large, unorganized collection of text, you’ll have your own magical lens to reveal its hidden structure. You, my chef, are more than ready now to make your smoothie recipe too :)</p><p>(Refer to my github repository where I implemented this from scratch, for a better understanding.— <a href="https://github.com/YashDaga874/FROM_SCRATCH_SERIES">https://github.com/YashDaga874/FROM_SCRATCH_SERIES</a>. It also contains visualizations so you can help yourself with them!)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f262fa72779a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>