<?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 Maria Burlando on Medium]]></title>
        <description><![CDATA[Stories by Maria Burlando on Medium]]></description>
        <link>https://medium.com/@Ayra_Lux?source=rss-5ed21d8eece5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*CDQVOwT4SrQHWH7R.jpg</url>
            <title>Stories by Maria Burlando on Medium</title>
            <link>https://medium.com/@Ayra_Lux?source=rss-5ed21d8eece5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 20:07:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Ayra_Lux/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[Balance that load!]]></title>
            <link>https://medium.com/@Ayra_Lux/balance-that-load-dfa18d0ea1fe?source=rss-5ed21d8eece5------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfa18d0ea1fe</guid>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[load-balancing]]></category>
            <category><![CDATA[load-balancer]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[virtual-machine]]></category>
            <dc:creator><![CDATA[Maria Burlando]]></dc:creator>
            <pubDate>Sun, 26 Jan 2020 15:43:16 GMT</pubDate>
            <atom:updated>2020-01-26T15:43:16.236Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*fCttjheCk5zre0KASfIZPQ.jpeg" /><figcaption>That’s how it’s done…</figcaption></figure><p>In this guide I’m going to show you how to set up a simple load balancer serving five nodes by configuring nginx on a computer.</p><p>Let’s suppose we’ve set up our virtual machine on a cloud platform such as AWS or Google Cloud Platform. We’ve decided to use Ubuntu 18.04 as our operating system.</p><p>We have connected to the machine with SSH connection, we’re writing commands like crazy, exploring all the hidden folders of our new remote machine…</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F13rQ7rrTrvZXlm%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F13rQ7rrTrvZXlm%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExemptdnFodGtpM2g4bjNxdTB5MHo3eXZzOGh1c2VqM3ZpNm41bTU1YiZlcD12MV9naWZzX2dpZklkJmN0PWc%2F13rQ7rrTrvZXlm%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="289" frameborder="0" scrolling="no"><a href="https://medium.com/media/75dc139e417f5e5745dfbca82c8c2a90/href">https://medium.com/media/75dc139e417f5e5745dfbca82c8c2a90/href</a></iframe><p>Now, we want to start serving the beautiful server application we should have developed. After all, you don’t set up a load balancer for nothing, do you?</p><p>The five nodes of our server application could be hosted on the same machine we’re working on, or they could be on another, or even on other five. It doesn’t change what we’re about to configure on this current virtual machine.</p><p>First things first, we need to install Nginx.</p><p>You’re probably going to go Jon Snowy on me saying:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fhas1WKhoorwLS%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fhas1WKhoorwLS%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fhas1WKhoorwLS%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2762eea4dd8afc93f6c5b03f82a54a3/href">https://medium.com/media/f2762eea4dd8afc93f6c5b03f82a54a3/href</a></iframe><p>But I’m just here to remind you of the wonderful guide that you can find on DigitalOcean:</p><p><a href="https://www.digitalocean.com/community/tutorials/how-to-install-nginx-on-ubuntu-18-04">How To Install Nginx on Ubuntu 18.04 | DigitalOcean</a></p><p>Leaving firewalls out of this post, the summary commands are:</p><pre>sudo apt update<br>sudo apt install nginx<br>systemctl status nginx</pre><p>Nginx should be active and running.</p><p>Once that’s done, we need to modify our configuration file for the nginx sites-enabled. We access the folder at:</p><pre>/etc/nginx/sites-enabled</pre><p>And we modify the whole content of the default file with the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a62c4cf2e7099c8cf1fbdf1d3d50257/href">https://medium.com/media/7a62c4cf2e7099c8cf1fbdf1d3d50257/href</a></iframe><p>The upstream loadbalancer block specifies the five IPs and ports of our nodes. As explained in the comments above, our nodes could be on localhost (127.0.0.1) or on different IPs if hosted on other machines (e.g. 34.66.22.102).</p><p>The ip_hash can be added to serve the same node that a user has previously accessed (i.e. same IP, same node).</p><p>The server name is currently localhost, but should be substituted with the domain name relative to our applcation (e.g. balancethatload.com).</p><p>The listen on port 80 is standard for HTTP connections.</p><p>While the remaining location block contains the location that the server should access which is redirected to the loadbalancer block.</p><p>Once the configuration is saved, we need to refresh Nginx:</p><pre>sudo systemctl stop nginx<br>sudo systemctl start nginx<br>sudo systemctl status nginx</pre><p>And if Nginx is active and running, the load balancer will serve your application on five different nodes just as expected.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FLJnA13jCK3K8g%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FLJnA13jCK3K8g%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FLJnA13jCK3K8g%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/a68a44806bbf7d73042e57696d780406/href">https://medium.com/media/a68a44806bbf7d73042e57696d780406/href</a></iframe><p>Yes, that’s it ;)</p><p>Hope you enjoyed this short post, and I’ll see you next time 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfa18d0ea1fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hidden Markov Models — Part 2: the Decoding Problem]]></title>
            <link>https://medium.com/@Ayra_Lux/hidden-markov-models-part-2-the-decoding-problem-c628ba474e69?source=rss-5ed21d8eece5------2</link>
            <guid isPermaLink="false">https://medium.com/p/c628ba474e69</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[viterbi-algorithm]]></category>
            <category><![CDATA[hidden-markov-models]]></category>
            <category><![CDATA[backtracking]]></category>
            <dc:creator><![CDATA[Maria Burlando]]></dc:creator>
            <pubDate>Thu, 03 Jan 2019 14:16:19 GMT</pubDate>
            <atom:updated>2019-01-03T14:16:19.751Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hidden Markov Models — Part 2: the Decoding Problem</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pzdo9ZSITNfE1xzxgrbYGw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/5ivJSXgZigY?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">fotografierende</a> on <a href="https://unsplash.com/search/photos/networks?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In my <a href="https://medium.com/@Ayra_Lux/hidden-markov-models-part-1-the-likelihood-problem-8dd1066a784e">previous article</a>, I have introduced the concept of Hidden Markov Model and solved the first Likelihood problem with the Forward and Backward algorithms.</p><p>If you haven’t still read it, I advise you to do so because what I’m going to explain in this article has foundations on the <a href="https://medium.com/@Ayra_Lux/hidden-markov-models-part-1-the-likelihood-problem-8dd1066a784e">previous</a>.</p><p>We have initialized Lea’s HMM as such:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*xufRsf74VdJH9Qa-UBizEA.jpeg" /></figure><p>And the model’s properties:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*5NY0eXf7FIQ3pn9c0f--Gg.png" /></figure><p>Let’s change what Lea has been doing in the past four days. Suppose she’s been shopping, cleaning, biking and painting. Our observation sequence would be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*Rw9H_rifd-9tx-zO2TYmPQ.png" /></figure><p>Given this new observation sequence, we’re going to be looking at the second problem of HMMs: the Decoding problem.</p><h3>Problem 2 — Decoding</h3><p>The Decoding problem is asking us to find the best sequence of hidden states <em>Q</em> given the observation sequence <em>O</em>.</p><p>So, if Lea’s been shopping, cleaning, biking and painting, how was the weather like during these four days?</p><p><strong><em>Q = ???</em></strong></p><p>To find the solution to this problem we’re going to make use of the Viterbi Algorithm.</p><h4>The Viterbi Algorithm</h4><blockquote>Like the forward algorithm, Viterbi is a kind of dynamic programming<br>that makes uses of a dynamic programming trellis.</blockquote><blockquote><a href="https://en.wikipedia.org/wiki/Dynamic_programming">Dynamic programming</a>: it refers to simplifying a complicated problem by breaking it down into simpler sub-problems in a <a href="https://en.wikipedia.org/wiki/Recursion">recursive</a> manner.</blockquote><p>And this is why, the Viterbi algorithm features similar steps to the forward algorithm: Initialization, Recursion and Termination, but also the Backtracking step to find the sequence of hidden states.</p><h4>Initialization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/219/1*ivOursUKAH-N48MBGoo_OA.png" /><figcaption>Viterbi Initialization Equation</figcaption></figure><p>If you’ve read attentively the previous article, the equation above should look quite familiar. It’s the same as the initialization equation of the Forward Algorithm.</p><p>Here we multiply the initial probability of state <em>i</em> by the emission probability from state <em>i</em> to observable <em>O</em> at time <em>t = 1 </em>(Shop)<em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*ytJool1pBNjjE1eiM8abhA.jpeg" /><figcaption>Initialization of Viterbi Algorithm</figcaption></figure><p>For the Sunny state, we multiply its initial probability, 0.6, with its emission probability to the observable Shop, 0.2. Hence, 0.12.</p><p>For the Rainy state, we multiply its initial probability, 0.4, with its emission probability to the observable Shop, 0.2. Hence, 0.08.</p><p>To retrieve the state sequence we also need to keep track of the argument which maximized for each <em>t</em> and<em> j, </em>i.e. the previous state that maximized the result of the equation<em>. </em>We do this via the array <em>ψ</em>, and in the initialization step the first <em>ψ</em> variable of every state will be equal to 0 because no specific argument coming from the initial probability maximized the value of the first state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/149/1*g2wueWFdXlkFl-TL5b04RQ.png" /><figcaption>Viterbi Initialization Array Equation</figcaption></figure><p><strong><em>ψ(Sunny) = [ 0 ]<br>ψ(Rainy) = [ 0 ]</em></strong></p><h4>Recursion</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*o4W1F5uBWnkMVA0ikEsDKw.png" /><figcaption>Viterbi Recursion Equation</figcaption></figure><p>Unlike in the Forward and Backward algorithms, in the Viterbi algorithm we’re not going to sum up the results of all the multiplications. Instead we’re going to find the maximum value among the multiplication results and assign that to the new Viterbi variable.</p><p>The multiplication consists of the previous Viterbi variable of state <em>i</em>, times the transition probability from state <em>i</em> to<em> j</em>, times the emission probability from state <em>j</em> to observation <em>O</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*bNpO0e9YSyYcNeArsaOfhg.jpeg" /><figcaption>Recursion of Viterbi Algorithm 1</figcaption></figure><p>In the case above, we’re choosing the highest value of two multiplications:</p><ul><li>Previous Viterbi variable of the previous Sunny state, 0.12, times the transition probability from Sunny to Sunny, 0.8, times the emission probability from Sunny to Clean, 0.1.<br><strong><em>0.12 * 0.8 * 0.1 = 0.0096</em></strong></li><li>Previous Viterbi variable of the previous Rainy state, 0.08, times the transition probability from Rainy to Sunny, 0.4, times the emission probability from Sunny to Clean, 0.1.<br><strong><em>0.08 * 0.4 * 0.1 = 0.0032</em></strong></li></ul><p><strong><em>0.0096 &gt; 0.0032 </em></strong>hence, <strong><em>δ = 0.0096</em></strong></p><p>As for the <em>ψ</em> array, we add the argument defined by the following equation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*I_7IGwjJktL3vylJjIR6Yw.png" /></figure><p>In the case above, the argument that maximized the Viterbi variable was the previous Sunny state that gave the result of 0.0096 for the Viterbi variable of the next Sunny state. Consequently, this Sunny state will be added to the array <em>ψ </em>of Sunny:</p><p><strong><em>ψ(Sunny) = [ 0, Sunny ]</em></strong></p><p>Similarly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*h2V8ksfaJLcsMXB0lO1fMw.jpeg" /><figcaption>Recursion of Viterbi Algorithm 2</figcaption></figure><p><strong><em>ψ(Rainy) = [ 0, Rainy ]</em></strong></p><p>And so on until we don’t have all the Viterbi variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*LFA2lZQlRt9kVM6eIIuZuQ.jpeg" /><figcaption>Recursion of Viterbi Algorithm 3</figcaption></figure><p><strong><em>ψ(Sunny) = [ 0, Sunny, Rainy, Sunny ]<br>ψ(Rainy) = [ 0, Rainy, Rainy, Sunny ]</em></strong></p><h4>Termination</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*j5PqcnRjFprjzD9K9iALHw.png" /></figure><p>This equation represents the probability of the entire state sequence up to point <em>T + 1</em> having been produced given the observation and the HMM’s parameters.</p><p>So, we need to find the maximized value among all Viterbi variables at time <em>T</em>, i.e. all the variables of every state at the end of the observation sequence. Hence, in our example above:</p><p>At time T the Sunny state has a Viterbi variable equal to 0.00082944, and the Rainy state has a Viterbi variable equal to 0.00015552.</p><p><strong><em>0.00082944 &gt; 0.00015552 =&gt; P = 0.00082944</em></strong></p><p>And the final element of the <em>ψ</em> arrays is Sunny because the argument that maximizes the following equation is Sunny:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*rjyL0yAYVSGuEnghWjRxrw.png" /></figure><p><em>ψ(Sunny) = [ 0, Sunny, Rainy, Sunny, </em><strong><em>Sunny</em></strong><em>]<br>ψ(Rainy) = [ 0, Rainy, Rainy, Sunny, </em><strong><em>Sunny</em></strong><em>]</em></p><h4>Backtracking</h4><p>The start of the backtrace corresponds to the last state of the hidden state sequence, and is given by the <em>ψ </em>equation at the termination step above, therefore, the <strong>Sunny state</strong>.</p><p>So, our hidden state sequence Q looks like this:<br><strong>Q = [ ?, ?, ?, Sunny ]</strong></p><p>The equation below is meant to find the hidden state sequence by backtracing through the <em>ψ</em> arrays.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*DMZwm4mkIOYFKgbWydxVFQ.png" /></figure><p>This might look very, very odd, but it’s explanation is very, very simple once you get the hang of it.</p><p>The <em>q*</em>s are the states of the state sequence we’re trying to find. So, when <em>t+1</em> is equal to <em>T</em> (the end of the sequence i.e. 4) the state <em>q*</em> is the last state Sunny.</p><p>Now, to find q* at time <em>t</em> we’re basically searching in the array <em>ψ </em>of the state <em>q*t+1 </em>at time<em> t+1.</em></p><p>Hold up, this is tricky.</p><p>Let’s look at our arrays <em>ψ:</em></p><p><em>ψ(Sunny) = [ 0, Sunny, Rainy, Sunny, Sunny ]<br>ψ(Rainy) = [ 0, Rainy, Rainy, Sunny, Sunny ]</em></p><p>The last state <em>q*</em> at time <em>t=4</em> is Sunny, so to find the hidden state at time <em>t=3</em> we search the array <em>ψ</em> of <strong>Sunny</strong> at time <em>t+1</em> i.e. <em>3+1=</em><strong><em>4</em></strong> . In this case, it’s Sunny again.</p><p><strong><em>ψ</em>(Sunny)</strong> = <em>[ 0, Sunny, Rainy, </em><strong><em>Sunny</em></strong><em>, Sunny ]</em></p><p>So, our <em>q*</em> at time <em>t=3</em> is Sunny.<br><strong>Q = [ ?, ?, Sunny, Sunny ]</strong></p><p>Now, if we want to find <em>q*</em> at time <em>t = 2</em>, we have to search the array <em>ψ </em>of<em> q*t=3 </em>(<strong>Sunny</strong>) at time <strong>3</strong>. In this case instead, it’s Rainy.</p><p><strong><em>ψ</em>(Sunny)</strong> = <em>[ 0, Sunny, </em><strong><em>Rainy</em></strong><em>, Sunny, Sunny ]</em></p><p>So, <em>q*</em> at time <em>t=2</em> is Rainy.<br><strong>Q = [ ?, Rainy, Sunny, Sunny ]</strong></p><p>Now instead, if we want to find q* at time t = 1, we search the array <em>ψ </em>of<em> q*t=2 </em>(<strong>Rainy</strong>) at time 2. This gives us <strong>Rainy</strong> again.</p><p><strong><em>ψ(Rainy) </em></strong><em>= [ 0, </em><strong><em>Rainy</em></strong><em>, Rainy, Sunny, Sunny ]</em></p><p>So, <em>q*</em> at time <em>t=1</em> is Rainy.</p><p>Consequently, if Lea’s observations sequence was:<br><strong><em> Shop =&gt; Clean =&gt; Bike =&gt; Paint</em></strong><br>Thanks to the backtracking step we now know the sequence of hidden states:<br><strong><em>Q = [ Rainy, Rainy, Sunny, Sunny ]</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*psavD3jRIOIPIdAdsLtAag.jpeg" /><figcaption>Hidden State Sequence derived from Backtracking</figcaption></figure><h3>Conclusion &amp; What’s next</h3><p>So, I know this was probably very hard, especially getting your head round the backtracking step, but I hope you guys managed to understand all of it. If not, let me know in the responses what doesn’t look clear.</p><h4>*Bonus tip for developers*</h4><p>Like in the previous article, I would like to share to every developer who’s reading this how to calculate the Viterbi algorithm with my <a href="https://www.npmjs.com/package/mary-markov"><strong>npm package called mary-markov</strong> </a>.</p><p>You can download the npm package <a href="https://www.npmjs.com/package/mary-markov"><strong>here</strong></a>, and see how I wrote the JavaScript code <a href="https://github.com/Mary62442/mary-markov"><strong>here</strong></a>.</p><p>Once you have installed it using npm install --save mary-markov you can write the following code in your index.js file and run it. This will solve you the Decoding problem by calculating the Viterbi Algorithm and backtracking through the hidden states.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ca7576498e3a18964bf7c3408a4d166/href">https://medium.com/media/5ca7576498e3a18964bf7c3408a4d166/href</a></iframe><h4>*********</h4><p>In the next article we’re going to be looking at the Learning problem of HMMs and how to solve it using the Baum-Welch algorithm.</p><p>I’ll see you next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c628ba474e69" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hidden Markov Models — Part 1: the Likelihood Problem]]></title>
            <link>https://medium.com/@Ayra_Lux/hidden-markov-models-part-1-the-likelihood-problem-8dd1066a784e?source=rss-5ed21d8eece5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8dd1066a784e</guid>
            <category><![CDATA[forward-algorithm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[hidden-markov-models]]></category>
            <category><![CDATA[backward-algorithm]]></category>
            <dc:creator><![CDATA[Maria Burlando]]></dc:creator>
            <pubDate>Sat, 29 Dec 2018 11:16:01 GMT</pubDate>
            <atom:updated>2019-01-03T13:49:00.489Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hidden Markov Models — Part 1: the Likelihood Problem</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pzdo9ZSITNfE1xzxgrbYGw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/5ivJSXgZigY?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">fotografierende</a> on <a href="https://unsplash.com/search/photos/networks?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>The traditional definition of HMM comes from Wikipedia’s unfailing support when it comes to searching a new topic:</p><blockquote><strong>Hidden Markov Model</strong> (<strong>HMM</strong>) is a <a href="https://en.wikipedia.org/wiki/Statistical_model">statistical</a> <a href="https://en.wikipedia.org/wiki/Markov_model">Markov model</a> in which the system being modeled is assumed to be a <a href="https://en.wikipedia.org/wiki/Markov_process">Markov process</a> with unobserved (i.e. <em>hidden</em>) states.</blockquote><p>And again, the definition for a Markov model:</p><blockquote>In <a href="https://en.wikipedia.org/wiki/Probability_theory">probability theory</a>, a <strong>Markov model</strong> is a <a href="https://en.wikipedia.org/wiki/Stochastic_model">stochastic model</a> used to <a href="https://en.wikipedia.org/wiki/Mathematical_model">model</a> randomly changing systems. It is assumed that future states depend only on the current state, not on the events that occurred before it (that is, it assumes the <a href="https://en.wikipedia.org/wiki/Markov_property">Markov property</a>).</blockquote><p>Hidden Markov Models application include <a href="https://en.wikipedia.org/wiki/Reinforcement_learning">reinforcement learning</a> and <a href="https://en.wikipedia.org/wiki/Time">temporal</a> <a href="https://en.wikipedia.org/wiki/Pattern_recognition">pattern recognition</a> such as <a href="https://en.wikipedia.org/wiki/Speech_recognition">speech</a>, <a href="https://en.wikipedia.org/wiki/Handwriting_recognition">handwriting</a>, <a href="https://en.wikipedia.org/wiki/Gesture_recognition">gesture recognition</a>, <a href="https://en.wikipedia.org/wiki/Part-of-speech_tagging">part-of-speech tagging</a>, musical score following, <a href="https://en.wikipedia.org/wiki/Partial_discharge">partial discharges</a> and <a href="https://en.wikipedia.org/wiki/Bioinformatics">bioinformatics</a>.</p><p>Now that we’ve got the fancy descriptions out of the way, we’re going to be looking at a rather simplified version of an HMM, so that our brains don’t have to start frying.</p><p>Let’s take Lea; Lea is our imaginary friend and during the day she does either of these four things:</p><ul><li>Painting</li><li>Cleaning the house</li><li>Biking</li><li>Shopping for groceries</li></ul><p>Not much of a life, is it? But anyway, this is a list of what are called <strong>observables</strong>. Now, let’s suppose that in four days Lea does the following: painting, cleaning, shopping, biking.</p><p>From this <strong>observation sequence</strong> we want to know whether the day has been sunny or rainy. These two are going to be our <strong>hidden states.</strong></p><p>Here is a graph of our potential HMM:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*xufRsf74VdJH9Qa-UBizEA.jpeg" /><figcaption>Lea’s Hidden Markov Model</figcaption></figure><p>To start off, a Hidden Markov Model consists of the following properties:</p><ul><li><strong>Hidden States <em>S</em></strong>: in the example above the hidden states are Sunny and Rainy, and they get grouped into a set S.</li><li><strong>Observables <em>O</em></strong>: Paint, Clean, Shop and Bike. They get grouped into a set O.</li><li><strong>Initial Probabilities 𝜋</strong>: a matrix of the initial likelihood of the state at time <em>t = 0</em>. In this case the likelihood that it is Sunny on the first day is 0.6, while the likelihood that it is Rainy is 0.4.<br><strong><em>𝜋 = |0.6, 0.4|<br></em></strong><em>Note: every row of the following matrices must add up to 1 since they represent a probability.</em></li><li><strong>Transition Probabilities <em>A</em></strong><em>: </em>a matrix that represents the probability of transitioning to another state given the current state. For example, if the current state is Sunny the probability that the day after is Sunny as well is 0.8, whereas the probability that the day after is Rainy is 0.2.<br>Similarly if today is Rainy, the probability that tomorrow is Rainy as well is 0.6, while the probability that tomorrow is Sunny is 0.4.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*26847PnlpEHdDsEOiDzwYg.jpeg" /><figcaption>Transition probabilities between states</figcaption></figure><ul><li><strong>Emission Probabilities <em>B: </em></strong>a matrix that represents the probability of seeing a specific observable given a hidden state. For example, the probability of Clean on a Sunny day is 0.1, whereas the probability of Clean on a Rainy day is 0.45.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*lYx0-vrpK128JY1oPgzUGw.png" /><figcaption>Emission probabilities</figcaption></figure><p>Under more mathematical terms, we would describe this model’s properties as such:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*5NY0eXf7FIQ3pn9c0f--Gg.png" /></figure><p>This is all very nice, but immediately we are faced with three problems:</p><ul><li>The Likelihood problem</li><li>The Decoding problem</li><li>The Learning problem</li></ul><p>In this first tutorial we’re going to analyse the first problem, which asks the likelihood of a certain observation sequence deriving from the HMM model that we have initialized.</p><h3>Problem 1 — Likelihood</h3><p>Let’s take the initial example about Lea’s activity in four days. The <strong>observation sequence</strong> is as follows: Paint, Clean, Shop and Bike.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*DQBfO5wmsMD2WjLlLtwtRA.png" /><figcaption>Observation sequence</figcaption></figure><p>So, what is the likelihood that this observation sequence <em>O</em> can derive from our HMM <em>λ</em>?</p><p><strong><em>P(O|λ) = ???</em></strong></p><p>There are two methods with which we can calculate this: the Forward Algorithm and the Backward Algorithm.</p><h4>The Forward Algorithm</h4><p>The Forward algorithm comprises of three steps:</p><ul><li>Initialization</li><li>Recursion</li><li>Termination</li></ul><h4>Initialization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/1*FAyre4vvFYNdFqI4z45_vw.png" /><figcaption>Forward algorithm initialization equation</figcaption></figure><p>The above equation means that the first forward variable is calculated by multiplying the initial probability of state <em>i</em> by the emission probability <em>b </em>of that state given the observable <em>O</em> at time 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*_exluVaLrekg8DXI1BGRvA.jpeg" /><figcaption>Initialization of Forward Algorithm</figcaption></figure><p>As can be seen the initial forward variable of the Sunny state is the initial probability of Sunny, 0.6, times the emission probability from Sunny to the observable Paint, 0.4. Hence, 0.24.</p><p>While the initial forward variable of the Rainy state is the initial probability of Rainy, 0.4, times the emission probability from Rainy to the observable Paint, 0.3. Hence, 0.12.</p><h4>Recursion</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*NuoQbI6QRVlK0OBrKQeIEA.png" /><figcaption>Forward algorithm recursion equation</figcaption></figure><p>For <em>t = 1, 2, …, T-1 </em>we make use of the recursion equation which defines the forward variable of state <em>j</em> as the product of the previous forward variable of state<em> i,</em> multiplied by the transition probability <em>a</em> between the previous state <em>i</em> to state <em>j</em>, multiplied by the emission probability <em>b</em> from state <em>j</em> to the observable <em>O</em>.</p><p>Mind frying, I know, but let’s have a look at the diagram below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*5526f59eXVIMf_4RYDqCgQ.jpeg" /><figcaption>Recursion of Forward Algorithm 1</figcaption></figure><p>Here we are calculating the forward variable of state Sunny at time 2 by summing the results of two multiplications:</p><ul><li>The previous forward variable of the previous Sunny state, 0.24, times the transition probability from Sunny to Sunny, 0.8, times the emission probability from Sunny to Clean, 0.1.<br><strong>0.24 * 0.8 * 0.1 = 0.0192</strong></li><li>The previous forward variable of the previous Rainy state, 0.12, times the transition probability from Rainy to Sunny, 0.4, times the emission probability from Sunny to Clean, 0.1.<br><strong>0.12 * 0.4 * 0.1 = 0.0048</strong></li></ul><p>Then, according to the equation above, we sum these results and get our forward variable.</p><p><strong>α = 0.0192 +0.0048 = 0.024</strong></p><p>Similarly, for the next step we’ll have a forward variable of 0.054 for the Rainy state:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*snkqLYgXDjgIZA1XP1wHRA.jpeg" /><figcaption>Recursion of Forward Algorithm 2</figcaption></figure><p>And so on until we have all the forward variables:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*7nG4new6SMd_54NkryRuCQ.jpeg" /><figcaption>Recursion of Forward Algorithm 3</figcaption></figure><h4>Termination</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/1*hI1meeZE-sW8Th-7i5y63Q.png" /><figcaption>Termination</figcaption></figure><p>This final equation tells us that to find the probability of an observation sequence <em>O </em>deriving from an HMM model <em>λ</em>, we need to sum up all the forward variables at time T, i.e. all the variables of every state at the end of the observation sequence. Hence, in our example above,</p><p><strong><em>P(O|λ) = 0.0028512 + 0.0003048 = 0.003156</em></strong></p><h4>The Backward Algorithm</h4><p>Usually, to find the solution to the Likelihood problem we don’t really require to know the Backward Algorithm. However, its explanation and resolution is a good litmus test to show that the Forward algorithm works proficiently, and moreover, by understanding it now, we can be ready for when the time will come to use it for the resolution of the third problem of Learning.</p><p>The Backward Algorithm is similar to the Forward algorithm, but like the name suggests it goes backward in time. There’s again an Initialization, a Recursion and a Termination.</p><h4>Initialization</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/144/1*DSQNeTbf_sMVDGNjvYWf6w.png" /><figcaption>Initialization</figcaption></figure><p>What this simple equation is telling us is that at time T (at the end of the observation sequence) the backward variables of every state is equal to 1. Simple as that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*-iY1zoclOIdEgLYBFcvNjg.png" /><figcaption>Initialization of Backward Algorithm</figcaption></figure><h4>Recursion</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*TDrnrD5pLZ9qXVn2jhpOfw.png" /><figcaption>Recursion</figcaption></figure><p>The equation above tells us to sum up all the multiplications of the transition probability from the current State <em>i</em> to the next State <em>j</em>, times the emission probability of the observable <em>O </em>at time<em> t+1</em> from the next State <em>j</em>, times the backward variable of the next State <em>j</em> at time <em>t+1</em>.</p><p>It might not look extremely clear, but let’s analyze the diagram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*MUpsl_tqBdoJhJg14ZghVQ.jpeg" /><figcaption>Recursion of Backward Algorithm 1</figcaption></figure><p>We’re going back in time. At time T where the final observable in the observation sequence was Bike, the backward variables have been initialized as equal to 1.</p><p>By going backwards we’re going to calculate the backward variable of the previous Sunny state. This consists of summing up two multiplications:</p><ul><li>Transition probability from Sunny to Sunny, 0.8, times the emission probability of Bike deriving from the Sunny state at time <em>t+1</em>, 0.3, times the backward variable of the Sunny State at time <em>t+1</em>, 1. <br><strong>0.8 * 0.3 * 1 = 0.24</strong></li><li>Transition probability from Sunny to Rainy, 0.2, times the emission probability of Bike deriving from the Rainy state at time <em>t+1</em>, 0.05, times the backward variable of the Sunny State at time <em>t+1</em>, 1. <br><strong>0.2 * 0.05 * 1 = 0.01</strong></li></ul><p>Then, according to the equation above, we sum these results and get our backward variable.</p><p><strong>β = 0.24 +0.01 = 0.25</strong></p><p>Similarly for the Rainy state:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*3jpRW2OUJDLCDNgGNCni5w.jpeg" /><figcaption>Recursion of Backward Algorithm 2</figcaption></figure><p>Like before, this is what we’re going to sum up:</p><ul><li>Transition probability from Rainy to Sunny, 0.4, times the emission probability from the Sunny state to Bike at time <em>t+1</em>, 0.3, times the backward variable of the Sunny State at time <em>t+1</em>, 1. <br><strong>0.4 * 0.3 * 1 = 0.12</strong></li><li>Transition probability from Rainy to Rainy, 0.6, times the emission probability from the Rainy state to Bike at time <em>t+1</em>, 0.05, times the backward variable of the Sunny State at time <em>t+1</em>, 1. <br><strong>0.6 * 0.05 * 1 = 0.03</strong></li></ul><p><strong>β = 0.12 +0.03 = 0.15</strong></p><p>And so on until we have all the backward variables:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*rxmdKOWGraKqqbiA0mqn1Q.jpeg" /><figcaption>Recursion of Backward Algorithm 3</figcaption></figure><h4>Termination</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*xJBRg6AZD4Xvjb25DS2mOw.png" /><figcaption>Termination</figcaption></figure><p>What this equation wants us to do is to sum the multiplications of the initial probability <strong><em>π</em> </strong>of state <em>i</em>, times the emission probability <em>b</em> of the observable <em>O</em> at time <em>t=1</em> from state <em>i</em>, times the backward variable at time<em> t=1</em> of state <em>i</em>.</p><p>Let’s clarify this in the diagram below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*IHkH0ufkctFn3IjzRV6-jQ.jpeg" /><figcaption>Termination of Backward Algorithm</figcaption></figure><p>As we can see, I have highlighted the probabilities we’re going to need to calculate our final probability.</p><p>As per equation we’re going to sum the following multiplications:</p><ul><li>The initial probability <strong><em>π </em></strong>of the Sunny state, 0.6, times the emission probability from Sunny state at time <em>t=1</em> to the observable Paint, 0.4, times the backward variable of the Sunny state at time <em>t=1</em>, 0.0071.<br><strong>0.6 * 0.4 * 0.0071 = 0.001704</strong></li><li>The initial probability <strong><em>π </em></strong>of the Rainy state, 0.4, times the emission probability from Rainy state at time <em>t=1 </em>to the observable Paint, 0.3, times the backward variable of the Rainy state at time <em>t=1</em>, 0.0121.<br><strong>0.4 * 0.3 * 0.0121 = 0.001452</strong></li></ul><p><strong>P(O|λ) = 0.001704 + 0.001452 = 0.003156</strong></p><p>And as we can see, the result is the same as that of the Forward Algorithm.</p><h3>Conclusion &amp; What’s next</h3><p>To finalize what we’ve learned we can say that the probability that Lea has spent the last four days painting, cleaning, shopping and biking, is 0.003156 given the HMM model we have built for her.</p><h4>*Bonus tip for developers*</h4><p>I know that these calculations are pretty hard to do by hand, and that is why I’m also offering you to play around the Lea example in JavaScript. I have created an <a href="https://www.npmjs.com/package/mary-markov"><strong>npm package called mary-markov</strong> </a>that solves all the problems of an HMM using the algorithms required.</p><p>You can download the npm package <a href="https://www.npmjs.com/package/mary-markov"><strong>here</strong></a>, and see how I wrote the JavaScript code <a href="https://github.com/Mary62442/mary-markov"><strong>here</strong></a>.</p><p>Once you have installed it using npm install --save mary-markov you can write the following code in your index.js file and run it. This will solve you the Likelihood problem by calculating the Forward and Backward Algorithms.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75473965c1302e7ec768836c99ff4d43/href">https://medium.com/media/75473965c1302e7ec768836c99ff4d43/href</a></iframe><h4>*********</h4><p>If you’ve managed to read up to this point, well done! This was certainly a hard one.</p><p>Unfortunately, it’s only the beginning of the HMM saga. In the next article we’re going to be looking at the Decoding problem of HMMs and how to solve it using the Viterbi Algorithm.</p><p>So, stick around, fellas!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8dd1066a784e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Guide to ORM Sequelize]]></title>
            <link>https://medium.com/@Ayra_Lux/a-guide-to-orm-sequelize-c276c7b6dd18?source=rss-5ed21d8eece5------2</link>
            <guid isPermaLink="false">https://medium.com/p/c276c7b6dd18</guid>
            <category><![CDATA[orm]]></category>
            <category><![CDATA[sequelize]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Maria Burlando]]></dc:creator>
            <pubDate>Mon, 17 Dec 2018 16:37:02 GMT</pubDate>
            <atom:updated>2018-12-17T18:23:29.412Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ri49w8TcHeXrnmO5dD4_aQ.jpeg" /></figure><p>A few days ago, I started trying to figure out Sequelize, a promise-based ORM for NodeJS. I have always been a fan of JavaScript; it was the first programming language I started studying when I was only 15, along with — surprise, surprise — HTML5 and CSS3.</p><p>Suffice to say, I wanted to try and find the best ORM solution for NodeJS. After all, C# has Entity Framework and Java has Hibernate, so it was ripe time to find one for Node as well. I made my first search and found <a href="https://www.npmjs.com/package/sequelize">Sequelize</a> to have around 250,000 downloads per week on npm. Not bad…</p><p>I started reading the documentation with its <a href="http://docs.sequelizejs.com/manual/installation/getting-started.html">Getting Started</a> section. It looked easy and fun, the code flowing out of me like a rivulet in spring, but then I arrived at a point where all my attempts just snagged on a barb in the documentation. I couldn’t for the life of me create a foreign key constraint in the PostgreSQL database I was using despite all the associations I wrote in my code. And so, for a whole morning, this is what I did to my computer:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FvjmSleUsnXU8o%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FvjmSleUsnXU8o%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FvjmSleUsnXU8o%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="185" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb66c2e1632e4fd3fa9ee9459a498842/href">https://medium.com/media/fb66c2e1632e4fd3fa9ee9459a498842/href</a></iframe><p>When I finally got to the Migration section of the documentation, you can‘t imagine what my reaction was to find out I had started it all wrong. When I finally found how easy it was to use the <a href="https://www.npmjs.com/package/sequelize-cli">Sequelize CLI</a>, it all became a piece of cake. That is, if you’re ready to scour the Internet for every little information that is missing from the real Sequelize documentation; you have to forsake everything: how hungry you’re starting to grow, how the laundry starts piling up in the corner, how the house starts catching fire…</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F13HgwGsXF0aiGY%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F13HgwGsXF0aiGY%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExamJ2aDR3YWNvazltZ243MzA5Y2UxNWtvcmN2aHNkd2s0cDdoejYxciZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F13HgwGsXF0aiGY%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/36bab17e7cb6b5565e779b07f2d18b53/href">https://medium.com/media/36bab17e7cb6b5565e779b07f2d18b53/href</a></iframe><p>But in the end, I did it! And this is why I decided to share this tutorial in order to help others set up Sequelize with clear understanding of the process.</p><p>So, here we go!</p><h4>How to set up a NodeJS application with Sequelize/Sequelize CLI</h4><p>First things first, in an empty folder we initialize npm —<em> duh!</em></p><pre>npm init</pre><p>Then we’re going to install Sequelize:</p><pre>npm install --save sequelize</pre><p>And the database we would like to use. In this case I’m using PostgreSQL.</p><pre>npm install --save pg pg-hstore</pre><p>This is described in the <a href="http://docs.sequelizejs.com/manual/installation/getting-started.html">Getting Started section</a> of the Sequelize documentation, which I would like to rename as <em>“Getting Stranded”</em>.</p><p>However, we want to do much better than play around with fancy little methods. We want to install the Sequelize CLI.</p><p>My advice is to install it locally because if you install it globally you’ll also have to install Sequelize and PostgreSQL globally because it will not be able to resolve them. So, in our application folder we write:</p><pre>npm install --save sequelize-cli</pre><p>And to initialize sequelize we write:</p><pre>node_modules/.bin/sequelize init</pre><p>This will do some Bibbidi-bobbidi-booing in our folder (I’ll call it applicationFolder) and create this schema for us:</p><pre>applicationFolder<br>  |-config<br>     |-config.js<br>  |-models<br>     |-index.js<br>  |-migrations<br>  |-seeders</pre><p>The index.js in models you don’t have to touch it because it’s all logic to render the models available, and other cool stuff. But the config.js is really interesting because there is where you can configure the databases you’re going to use for the three environments of development, testing and production.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a292b9de568e365c9f04352bba6419df/href">https://medium.com/media/a292b9de568e365c9f04352bba6419df/href</a></iframe><p>For my development environment, I’ll be changing it like so:</p><pre>&quot;development&quot;: {    <br>    &quot;username&quot;: &quot;postgres&quot;,     <br>    &quot;password&quot;: &quot;secret&quot;,     <br>    &quot;database&quot;: &quot;postgres&quot;,     <br>    &quot;host&quot;: &quot;127.0.0.1&quot;,     <br>    &quot;dialect&quot;: &quot;postgres&quot;   <br>}</pre><p>And this is how you set up Sequelize and Sequelize CLI in your NodeJS application.</p><h4>Create your models and migrations</h4><p>Now, for this application we want to create two models in the database: a Product and a Category.</p><p>Sequelize CLI has lots of handy commands, but we want to start and create a new Product model with a sku, a name, and a price. To do this we use:</p><pre>node_modules/.bin/sequelize model:generate --name Product --attributes sku:string,name:string,price:double</pre><p><em>Note: the name and attributes are compulsory.</em></p><p>This will create a product.js file in the models folder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b358db945a760a9f623f8e4265496b79/href">https://medium.com/media/b358db945a760a9f623f8e4265496b79/href</a></iframe><p>And a corresponding migration XXXXXXXXXXXXXX-create-product.js file in the migrations folder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95c6d9b0e2e7e386f42d30011f319038/href">https://medium.com/media/95c6d9b0e2e7e386f42d30011f319038/href</a></iframe><p><em>Note: The up function is used to actuate the migration, whereas the down function is used to undo the migration.</em></p><p>Until now, we haven’t inserted anything in the database, so we’re going to migrate this cool stuff and write the model in our PostgreSQL database.</p><pre>node_modules/.bin/sequelize db:migrate</pre><p>As per <a href="http://docs.sequelizejs.com/manual/tutorial/migrations.html">documentation</a>:</p><blockquote>This command will execute these steps:</blockquote><blockquote>* Will ensure a table called SequelizeMeta in database. This table is used to record which migrations have run on the current database</blockquote><blockquote>* Start looking for any migration files which haven’t run yet. This is possible by checking SequelizeMeta table. In this case it will run XXXXXXXXXXXXXX-create-product.js migration, which we created in last step.</blockquote><blockquote>* Creates a table called Products with all columns as specified in its migration file.</blockquote><p>If we want to undo the migration, we type:</p><pre>node_modules/.bin/sequelize db:migrate:undo</pre><p>Moving on, we’re going to create the Category model with a name and a description.</p><pre>node_modules/.bin/sequelize model:generate --name Category --attributes name:string,description:string</pre><p>As with the Product model we’ll get a category.js in the models folder and a XXXXXXXXXXXXXX-create-category.js in the migration folders.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae569129abc60ae5cf92fcc9ec7dfe87/href">https://medium.com/media/ae569129abc60ae5cf92fcc9ec7dfe87/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b092c061ac75f0ae136dd25b79423ef2/href">https://medium.com/media/b092c061ac75f0ae136dd25b79423ef2/href</a></iframe><p>And again, to migrate this model to PostgreSQL, we type:</p><pre>node_modules/.bin/sequelize db:migrate</pre><p><em>Note: instead of doing two migrations we could have generated the two models first, and then executed the above command. Migrations run in order of creation.</em></p><h4>Creating associations and foreign keys</h4><p>What I want to do for these two models is to associate them.</p><p>Each product should belong to one category (hypothetically). So, we want a relationship one-to-many between category and products.</p><p>If you note in the product.js file in the models folder you’ll see a method like this:</p><pre>Product.associate = function(models) {    <br>    // associations can be defined here  <br>};</pre><p>As per Sequelize documentation we’ll be substituting the comment with this:</p><pre>Product.associate = function(models) {    <br>    Product.belongsTo(models.Category);  <br>};</pre><p>When you start studying Sequelize, you’re supposed to sync your table after defining it and after defining its associations with the sync() function, but that doesn’t work if you want to make a foreign key constraint in the database.</p><p>So, what you do instead, is create a new migration file and add a new column to the Product model which will write the CategoryId as foreign key in the database.</p><pre>node_modules/.bin/sequelize migration:generate --name add-prod-cat-association</pre><p>You’ll find a new empty migration file in the migrations folder called XXXXXXXXXXXXXX-add-prod-cat-association.js where you’ll write the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50732dfa64c8cc5a1d737d507ecca732/href">https://medium.com/media/50732dfa64c8cc5a1d737d507ecca732/href</a></iframe><p><em>Note: the type of the foreign key must be equal to the type of the key in the Target model, in this case </em><em>Sequelize.INTEGER.</em></p><p>We run:</p><pre>node_modules/.bin/sequelize db:migrate</pre><p>And in your database underneath the rest of the Product properties, you’ll finally have this very satisfying result:</p><pre>&quot;CategoryId&quot; integer,<br>  CONSTRAINT &quot;Products_pkey&quot; PRIMARY KEY (id),<br>  CONSTRAINT &quot;Products_CategoryId_fkey&quot; FOREIGN KEY (&quot;CategoryId&quot;)<br>      REFERENCES public.&quot;Categories&quot; (id) MATCH SIMPLE<br>      ON UPDATE CASCADE ON DELETE SET NULL</pre><p>Ok, now you’re going to tell me, “This is really cool, but how am I going to write stuff inside it, and all the things a developer is supposed to do with databases? Do I have to write migration after migration?”</p><p>My dear, now we can go back to the <em>“Getting Stranded”</em> section because we’re finally able to write some good stuff.</p><h4>Insert data into our database</h4><p>First of all, we’re going to create an index.js file in our root folder. This is where, if needed, we’ll work with Express, body-parser, cookie-parser, and where we’ll write our routes. But for the time being, let’s suppose it’s just a simple JavaScript file that, like a child, likes to play around with a few basic functions.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FAxMaQkk4Uouyc%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FAxMaQkk4Uouyc%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FAxMaQkk4Uouyc%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="306" frameborder="0" scrolling="no"><a href="https://medium.com/media/0fe7a2823e5699077576f5a26da88005/href">https://medium.com/media/0fe7a2823e5699077576f5a26da88005/href</a></iframe><p>In the index.js file we’re going to import the following:</p><pre>const models = require(&#39;./models&#39;);<br>const Op = models.Sequelize.Op;</pre><p><a href="http://docs.sequelizejs.com/manual/tutorial/querying.html"><em>Note: Op is required to make operations in queries.</em></a></p><p>If you want to check that the models are now available, you can write a simple function like:</p><pre>models.Product.findAll().then(pr =&gt; console.log(pr))</pre><p>However, if you try to run it, you’ll get the error:</p><pre>ReferenceError: Sequelize is not defined</pre><p>To fix this you need to write the following in every file in the models folder. In this case in product.js and in category.js.</p><pre>var Sequelize = require(&#39;sequelize&#39;);</pre><p>Now, it should work, and of course the result will be an empty array because there is nothing in our database yet.</p><p>Let’s instead create a function that accepts an object category and an array of object products. We want this function to create a new row in the categories table in our PostgreSQL database with the new category object, while also creating new rows in the products table for each product object in the product array. Of course, this method should be called when every product in the array corresponds to the category object that is being passed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d037c0b57ad51f843a3f83a8c3d140b0/href">https://medium.com/media/d037c0b57ad51f843a3f83a8c3d140b0/href</a></iframe><p>What this function does is to create a category with the data the method receives, and save its newly generated id in catId. Then, we map the array of products and create new rows in the products table in the PostgreSQL database where we’ll also be setting the product’sCategoryId corresponding to catId.</p><p>An example of this function’s usage would be:</p><pre>let newCategory = {<br>    name: &quot;Fantasy&quot;, <br>    description:&quot;Fantasy genre of the book&quot;<br>};</pre><pre>let newProducts = [<br>    {<br>     sku: &quot;nvw1&quot;,<br>     name: &quot;Neverwhere&quot;,<br>     price: 10.99<br>    },<br>    {<br>     sku: &quot;nrl2&quot;,<br>     name: &quot;Northern Lights&quot;,<br>     price: 8.99    <br>}<br>];</pre><pre>CreateCatWithProds(newCategory, newProducts)</pre><p><em>(This is just an example of course. It would have made more sense to create a Book model rather than a Product, but it doesn’t matter now.)</em></p><p>This is one way to do this, but according to the Sequelize documentation there are many more methods available.</p><p>For the sake of this tutorial I’ll be stopping here.</p><h4>A final word</h4><p>Sequelize is great, but it’s important that we understand migrations first if we want to write clear structural database operations, like adding tables, columns, etc; unless we don’t want to end up like this angry panda midway Sequelize “<em>Getting Stranded”</em> section.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FP63ufnr888Sf6%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FP63ufnr888Sf6%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FP63ufnr888Sf6%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="245" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e1fc4fe4c92952a7869e97313f8c31b/href">https://medium.com/media/0e1fc4fe4c92952a7869e97313f8c31b/href</a></iframe><p>So, I hope this tutorial will help you understand better the process of setting up Sequelize for your NodeJS application, and not run into unnecessary problems along the way — like I did.</p><p>Have a great day, Sequelizers!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F2w4LQxIPG5odLqw93a%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F2w4LQxIPG5odLqw93a%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F2w4LQxIPG5odLqw93a%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="181" frameborder="0" scrolling="no"><a href="https://medium.com/media/eadc7f89ef870f89c417ed7a86a635ab/href">https://medium.com/media/eadc7f89ef870f89c417ed7a86a635ab/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c276c7b6dd18" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>