<?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 Thiago Lira on Medium]]></title>
        <description><![CDATA[Stories by Thiago Lira on Medium]]></description>
        <link>https://medium.com/@thiago-lira?source=rss-afeea1f90ef6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*iIGAfaVCSQOMIzY2.</url>
            <title>Stories by Thiago Lira on Medium</title>
            <link>https://medium.com/@thiago-lira?source=rss-afeea1f90ef6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 03:14:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thiago-lira/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[How not to pay Adobe and process multiple photos with Python (using the GPU no less!)]]></title>
            <link>https://thiago-lira.medium.com/how-not-to-pay-adobe-and-process-multiple-photos-with-python-using-the-gpu-no-less-169c59c1c9ce?source=rss-afeea1f90ef6------2</link>
            <guid isPermaLink="false">https://medium.com/p/169c59c1c9ce</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[photoshop]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[photography]]></category>
            <dc:creator><![CDATA[Thiago Lira]]></dc:creator>
            <pubDate>Wed, 23 Nov 2022 21:48:37 GMT</pubDate>
            <atom:updated>2022-11-23T21:48:37.109Z</atom:updated>
            <content:encoded><![CDATA[<p>There is a very elegant technique to remove crowds from photos in which you just use a tripod and take multiple photos from the exact same spot. Every single picture might have tons of people, but every picture has people in different spots! So if you just average the pixels most of the crowd will just disappear. (Technically, the median works better, but I’m getting ahead of myself).</p><p>I took both of these pictures in the Zu lai Temple located in Cotia, Brazil. Notice that both have people passing by but in slightly different spots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qplnQcZCEY1LEoC5TACjKw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ay8iNGLR0qSfhV7xT3IyaA.jpeg" /></figure><p>Photoshop has a feature that lets you select a bunch of pictures, “stack” them, and then apply some function to aggregate it’s pixels, like the mean or median. But honestly, I pay Adobe way to much money already for Lightroom, which is the software I use to develop my photos. And even worse, they make you go for the package with the cloud storage you don’t even need just to gain access to Lightroom and it doesn’t come with Photoshop and you have to pay MONTHLY.</p><p>NOT TODAY ADOBE. I will take my own median from my own goddamn pixels thank you very much.</p><p>It’s all very straightforward: When you use a library like PIL you can load any .jpg file in Python like a numpy array with the dimensions:</p><pre>(WIDTH, HEIGHT, RGB)</pre><p>We want to stack all photos I took from the same place in the same array, or, simply:</p><pre>all_images = np.stack(img_list)</pre><p>So, now, our array dimensions are like so:</p><pre>(N_IMAGES, WIDTH, HEIGHT, RGB)</pre><p>Giving a concrete example, one of the pictures I produced came from an array with dimensions (17, 4160, 6240, 3), which means that I stacked data from 17 pictures, each having 4160x6240 pixels with 3 colors each (the RGB channels).</p><p>Now it is just a question of taking the median, but it is easy to get lost of what exactly we are taking the median of with so many dimensions.</p><p>Imagine we are aligning the pixels of 17 images and for each aligned pixel we will just take the median from the 17 RGB values (element-wise), which are of course a triple of 3 colors, so our median for each pixel will be the result of an expression similar to this one:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/0*3YSgg331N1-wAJbc.png" /></figure><p>So, the expression in Numpy of Pytorch to perform this calculation along the first dimension (the stacked images) is as follows:</p><pre>result = np.median(all_images, axis=0)</pre><p>And we get back a result which is a single image, with dimensions (1, 4160, 6240, 3), ready to be exported.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OAmiELehl6xq9eMQeSzypQ.jpeg" /><figcaption>That little crowd on the right and the woman on the left are gone!</figcaption></figure><p>No person in sight! Well, almost. The result would have been better if I had taken more pictures, but this was just to prove a point.</p><p>And to be even more pedantic about it, I wrote code to do the exact same thing using the CPU (on Numpy) and the GPU (on PyTorch), it took 5s to process this image on my CPU and 2s on my GPU, not too bad!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=169c59c1c9ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Toy Diffusion model you can run on your laptop]]></title>
            <link>https://thiago-lira.medium.com/a-toy-diffusion-model-you-can-run-on-your-laptop-20e9e5a83462?source=rss-afeea1f90ef6------2</link>
            <guid isPermaLink="false">https://medium.com/p/20e9e5a83462</guid>
            <category><![CDATA[dalle-2]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[diffusion-models]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Thiago Lira]]></dc:creator>
            <pubDate>Thu, 04 Aug 2022 22:48:09 GMT</pubDate>
            <atom:updated>2022-08-07T15:49:04.586Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*Nv_K1Ul7VUwVwHeb7PIrQQ.gif" /></figure><p>It seems that it has become more and more common for niche new advancements in AI to break in to the mainstream media and to dazzle layman and practitioners alike with the amazing things one can achieve with Deep Learning.</p><p>The latest such occasion was OpenAI&#39;s amazing DALLE-2, the text to image model capable of generating an image for almost anything you can imagine, given that it can be described with text.</p><p>In this post I will code a toy model representing part of this amazing system. The Diffusion-based Decoder. I will focus on implementing it in Python and will try to use very little mathematical notation. <strong>This post is meant to help someone understand the technical aspects of the model, not the (amazing) mathematics behind it.</strong></p><h4>If you just want references and mathematical explanations of this model, I provide links on the next section. If you just want to see and run the code just go directly to my <a href="https://github.com/ThiagoLira/ToyDiffusion">repo</a>.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*llyJPWfh89ShqShcUctXng.jpeg" /><figcaption>&quot;Nietzsche and Jesus do a rap battle in the middle of a crowd&quot; (Image generated with Dalle-2 by me)</figcaption></figure><p>Even working in the field sometimes I just have to convince myself something is really true by coding some version of it myself, albeit a very simple one. So here it is.</p><p>There are <a href="https://www.assemblyai.com/blog/how-dall-e-2-actually-works/">many</a> excellent resources to learn about how Dalle-2 works. On this post I will focus on this one piece of mathematics that Dalle-2 is based upon called a <strong>diffusion model</strong>. Which is a model that learns to discern noise added to data (like which part of an image is blur) and surprisingly, can learn to remove this noise! And even more surprisingly, we can just use a diffusion model trained on this task of removing noise from images to <strong>create a new image from scratch </strong>by just removing <strong>noise from noise</strong> over and over, guided by some embedding (i.e. numerical representation) of what the image should look like. Again, this is quite involved and I think others resources can explain this process of creating and embeddings from text and converting it to a image embeddings much better than I can.</p><p>On the DALLE-2 pipeline this part is right at the end. Where the model has an image embedding and uses a diffusion based model to guide pure noise to become an image that represents this embedding, step by step.</p><h3>What **is** a diffusion model?</h3><p>All the rest of this post will be based upon the original proposal of diffusion models, by <a href="https://arxiv.org/abs/1503.03585">this work</a>. And an improvement on the training objective proposed by this <a href="https://arxiv.org/abs/2006.11239">other work</a>. If you want a simple yet more comprehensible deep dive in the mathematics behind this model, watch <a href="https://www.youtube.com/watch?v=fbLgFrlTnGU">these</a> <a href="https://www.youtube.com/watch?v=344w5h24-h8">excellent</a> videos.</p><h3>Our objective: Make a model learn to make a scatterplot that looks like Homer Simpson starting from pure noise!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*4U--0PPNQNqFhf5cM64etw.jpeg" /><figcaption>Our initial data.</figcaption></figure><h4>The big picture without much mathematical notation:</h4><p>The whole process is composed of 2 steps:</p><p>a) We add T &quot;steps&quot; of noise to the data (e.g. multiply every point by a random number), and train the model try to predict how many steps T you added to the data, and do many backpropagation iterations with many many Ts. We will have a schedule of how much randomness we will add on every step, so that we can calculate each step directly from the data. Although we are using random numbers, data corrupted by 50 steps of noise will look alike other data corrupted by the same amount.</p><p>We select a maximum number of steps of noise you can add to the data. Normally something around 1000 (Let&#39;s call this number N). At this point we have some nice mathematical properties because we can assume that we turned our data into something indistinguishable from pure noise.</p><p>We will call this the <strong>forward process</strong>.</p><p>b) After the model is good at task a), you can give pure noise to the model and ask it to remove N steps of noise from it. Ideally the model will get the pure noise to look like the original data you used on the first task.</p><p>We will call this the <strong>reverse process.</strong></p><h4>A Mathematical Interlude to formalize things a little bit:</h4><p>(You can skip this part if you want, I will try my best to use less mathematical notation in the following sections)</p><p>The forward and the reverse processes are Markov Chains.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*t1VXa617_OlVp0j33T0G8g.png" /><figcaption>The Forward Process</figcaption></figure><p>Given initial data X_0, we produce X_T (noise) by applying multiple Gaussian transitions (more on this on the next section). Each transition will apply a little Gaussian noise on X_t to generate X_t+1.</p><p>The reverse process is not so easy. We have some distribution p_theta that will do the opposite. We will try to find parameters (theta) to make this function gradually recover the data X_0 from pure noise X_T.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*U2w_Fh4yVA0qAtZXiyatDw.png" /><figcaption>The Reverse Process</figcaption></figure><p>Every <em>p</em> and <em>q</em> will be defined to be Multivariate Gaussians. This is the topic of the next section. Our objective will be to learn the means for our reverse process distributions <em>p</em>!</p><h3>The forward process:</h3><p>We first need a function to add noise to an initial data distribution. Which basically mean that we will take all our data points and wiggle each one by a random number. What does that mean in Python? Let&#39;s first familiarize ourselves with a Multivariate Normal Distribution. Skip the next couple paragraphs if you already know how such a distribution works.</p><p>Let&#39;s start with a single point on the plane.</p><p>Say we want to take some point and randomly move it a little bit on the 2D plane. If the point is on coordinates (x1,y1), we sample 2 small random numbers 𝜀_1 and 𝜀_2 and we move the point to it&#39;s new location (x1 + 𝜀_1, x2 + 𝜀_2).</p><p>A Multivariate Normal Distribution is one such distribution to sample as many 𝜀&#39;s as we have data points. We will use our starting points as the mean of the distribution, which means (haha) that for every point (x_n, y_n) it&#39;s new position will be something like (x_n + 𝜀_1, y_n + 𝜀_2). And where does the 𝜀 comes from? From our covariance matrix, which is a fancy name to a big matrix that will have one variance for each point in our distribution, i.e. how small or big each 𝜀 will likely be.</p><p>The first function will just take our data, sample 𝜀&#39;s for each point and return the resulting data corrupted by those 𝜀’s.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/219fcd6ec649a3437a2e2c37cc1db15a/href">https://medium.com/media/219fcd6ec649a3437a2e2c37cc1db15a/href</a></iframe><p>This <em>list_bar_alphas</em> argument is just the amount of noise we will add for every step T of diffusion, which is the other argument of this function. For some <em>t </em>we will get the corresponding <em>alpha</em> from <em>list_bar_alphas, </em>and use this <em>alpha</em> to calculate the variance of our noise<em>. </em>For every step of diffusion we fix the parameters of the noise added to the model beforehand! These values came from the original paper.</p><p>Now let&#39;s see some actual data. Say we want to diffuse this scatter plot of Homer Simpson. This is how the plot will look if we apply diffusion for some numbers <em>t</em> of steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*ocj8TdaPauR4tAk-AkFyeQ.gif" /><figcaption>See how the more steps of noise we add to poor Homer, the more he looks like pure noise.</figcaption></figure><h4>Calculating the Posterior Distribution:</h4><p>This part is going to get a bit technical on the mathematical details. The code is simple to read but there is indeed a lot going on theory-wise. We have a forward process corrupting the data, which in mathematical notation is something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*kPGiprwvz9Wj3MpPag7k1A.png" /><figcaption>For every step t we will sample a more corrupted sample from this distribution. This is a Markov Chain generating new corrupted X’s from the original data X_0</figcaption></figure><p>This distribution is <strong>fixed</strong>. For any <em>t </em>we know exactly the distribution to sample X_t+1 from. But remember I wrote that we will try for each step to predict how much noise was added, right? So, and stay with me here, we want to predict the <strong>mean </strong>of<strong> </strong>the posterior distribution of <em>q</em>. In other words, the <strong>center</strong>, or the original data we had, like if we are walking backwards and removing the noise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*wpz38mJZnglmUr1Cu0Mm_Q.png" /><figcaption>Pay attention to the indexes! Our model will try to predict the mean of this distribution.</figcaption></figure><p>This is <strong>not</strong> the reverse process! If <em>q</em> is the distribution we parametrized to corrupt the data, <em>p</em> will be the distribution to recover the data, our model! And the clever mathematical insight from the papers I linked before is that we can assume that our reverse distribution will have the same functional form of the forward process. Which we defined to be simple! So it is enough for our model to be some function that tries to match the output of the posterior of <em>q </em>during training. And this is exactly what is happening in the training loop:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24d4bd2f25b6d0b4a59bbf5a277e992c/href">https://medium.com/media/24d4bd2f25b6d0b4a59bbf5a277e992c/href</a></iframe><p>Something important to understand, our posterior distribution q(x_t-1 | x_t) of the forward process is <strong>known</strong>! We just need some algebraic manipulation to calculate it. What is definitely not known is the other distribution <em>p</em>, the reverse process. It is easy to corrupt the data, it is very much not easy at all to get something like the data back from pure noise. The insight that I will not try to formalize here is that the functional form of the reverse process closely follows q(x_t-1 | x_t), which we can easily calculate. So we can assume it to be Gaussian as well. (*)</p><p>(*) For the mathematically keen among you, the paper indeed uses a KL Divergence term to approximate the reverse process distribution <em>p</em> to the known forward process distribution <em>q. </em>And it is from some clever manipulation that we get a simple loss target from that.</p><h3>The Reverse Process:</h3><p>Now for the fun part: We trained a model very good at discerning the noise from a corrupted sample produced by a known Gaussian distribution. Let&#39;s give it some random noise and see if it finds something resembling our traning data in it! We will run a loop, starting at random noise (<em>t</em>=N), to calculate the data at step <em>t</em>-1 until we supposedly should have the original data (<em>t</em>=0).</p><p>This is the function that does that inside this loop, we are just sampling from a Multivariate Normal Distribution with the next mean for the process predicted by the model, like I explained in the last section. Our model gives just the mean, the variance we define to be exactly the same from the forward process!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a9badb22b7e1406e9246ebdda36ff90/href">https://medium.com/media/4a9badb22b7e1406e9246ebdda36ff90/href</a></iframe><h3>Results:</h3><p>So starting with a 2D scatter plot of pure Gaussian noise I animated the reverse diffusion process the model learned! Here is this process in it&#39;s full GIF glory. Not bad, right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*Nv_K1Ul7VUwVwHeb7PIrQQ.gif" /><figcaption>The model finds something similar to the original data in pure Gaussian noise!</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*4U--0PPNQNqFhf5cM64etw.jpeg" /><figcaption>Our initial data.</figcaption></figure><p>If you want to play with the code, just clone my <a href="https://github.com/ThiagoLira/ToyDiffusion">repo</a> and run every cell on the notebook RunDiffusion.ipynb!</p><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20e9e5a83462" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Training a Reinforcement Learning agent to fish in Stardew Valley]]></title>
            <link>https://thiago-lira.medium.com/training-a-reinforcement-learning-agent-to-fish-in-stardew-valley-d4d0ebe77281?source=rss-afeea1f90ef6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4d0ebe77281</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[games]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Thiago Lira]]></dc:creator>
            <pubDate>Fri, 21 Jan 2022 18:08:37 GMT</pubDate>
            <atom:updated>2022-01-21T20:50:50.095Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*A1nOzbU4J3YvQ09O.gif" /><figcaption>Because actually learning to play a simple minigame wouldn’t make for a cool blog post</figcaption></figure><p>This is a project I have been grinding on and off for quite some time. I had never tried to mod a game and I had never successfully trained a “real” reinforcement learning agent (I gave up on Flappy Bird). The challenge for me was understanding exactly what was the “state space” of my problem. When you code using some easy RL framework that gives you the agent, the environment and the reward you don’t have to think at all about the modeling part of your problem. Within a game context you have to think about the state the model will read each frame and the inputs the model will feed to the game and then collect a suitable reward accordingly. You have to make sure that the model has the correct affordances inside the game (it sees <strong>only</strong> what the player sees), otherwise it could just learn to exploit a bug or break the game, or not converge at all.</p><p>My goal was to code an agent that would read the state of the fishing minigame and perfectly play the game. <strong>The end result is a mod for Stardew Valley, written in C# using the Official Stardew Valley’s modding API. The mod loads a serialized DQN model trained in Python.</strong> I first collected data from the game, then I used this data to train a simple DQN with Pytorch. After some iterations I can generate a serialized model with ONNX and I can then load the model from the C# side, and in every frame it receives as input the state of the fishing minigame and (hopefully) outputs the correct action on every frame.</p><h3>The Fishing Minigame</h3><p>This agent is written with the help of the fantastic SMAPI, the Official Stardew Valley’s modding API. The API gives access to the the game memory in runtime and provides everything I needed to make an agent that interacts with the game state and feeds an input to the game in real time.</p><p>In the fishing minigame you have to align the “hook” (a green bar) with the moving fish, you give the bar a little nudge up by clicking with the left mouse button. The fish moves erratically in this vertical bar. Every frame that you manage to align the hook bar with the fish the green bar fills up a little bit, and if the fish manages to escape the green bar starts to empty. You catch the fish when you fill the green bar and lose the fish when it empties.</p><h3>The Reinforcement Learning problem</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*Q0iItIohAer14BazFXJ-uw.png" /></figure><p>So, I just need to read these specific attributes from the game’s memory every frame and save them as my state for the frame <em>t</em>. You can see the code for reading specific attributes from the game memory, for this problem I need the 4 variables the game keeps track during the fishing minigame. The position of the center of the “hook”, the position of the fish, the speed of the hook and the amount the green bar is filled (this is our reward!). The names the game uses internally are a little odd, but in this order, this is the code to read them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2a530b12828ec381e508af4ca6eb2d0/href">https://medium.com/media/b2a530b12828ec381e508af4ca6eb2d0/href</a></iframe><p>The first three define our state:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*9pS1sASa7o7B6yc9ho9UCg.png" /></figure><p>This is what the model can use on each frame to decide what it will do. To set this up as a Reinforcement Learning problem we also need a reward to guide training. The reward will be how much the green bar is filled, this is the variable <em>distanceFromCatching</em>. This goes from 0 to 1, and is perfect for a reward. The RL agent will hopefully learn to carry out the actions that will make it maximize it’s future reward (i.e. catch the fish).</p><h3>Replay Memory</h3><p>Replay Memory is a technique used in Q-learning to de-correlate the training to a specific “episode”. We do this by storing state transitions on a buffer and training the model by sampling random batches from this memory instead of training directly with the latest data. To train the model we need 4 things, respectively the current state, the next state, the action we took and the reward:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*LCGzt5ci9OVSn6RtkDYMgg.png" /></figure><p>The crux of Q-learning is to know which state you were, which state you got to, which action you took to get to this new state and the reward you got from performing this action. With thousands and thousands of these examples we can use a simple algorithm like Value Iteration (<a href="https://artint.info/html/ArtInt_227.html">a dynamic programming algorithm</a>) and <strong>propagate rewards from terminal states (winning states) to preceding states that leads to it</strong>, so for every possible state the model will know the direction that maximizes it’s future reward. I will not train the model with Value Iteration because real problems tend to have too many states and dynamic programming takes forever, but this is the idea of what is happening.</p><p>Just to illustrate, this is how I save each entry of my Replay Memory in C#. I use buffers to get the state and action from the last frame and store all of this together with the state and the reward from the present frame.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ba9efd882c2f889a9837fae458b4aa8/href">https://medium.com/media/6ba9efd882c2f889a9837fae458b4aa8/href</a></iframe><p>All this data becomes a huge csv file that I load via Python and use to train the DQN model.</p><h3>The Neural Network</h3><p>Q-learning using Neural Networks to estimate the Q-table is called <strong>Deep Q-Learning</strong>. The idea is very well explained in this <a href="https://pytorch.org/tutorials/intermediate/reinforcement_q_learning.html">Pytorch Tutorial</a>, from where I mercilessly stole all the code and changed it a bit for my problem. The main idea is that we will use two neural networks. One will estimate the value of the <em>Q(s,a) </em>(Policy Net), the other to estimate the value of the future Q-values (Target Net). We then backpropagate on the difference of both these networks.</p><p>Here is the basic equation for the Q-learning algorithm. We will use one network to estimate the correct value of the current state <em>Q(s,a)</em>, the other one will estimate the maximum possible value for the next state. Both networks are initialized with random values and every few iterations we <strong>copy </strong>the Policy Net weights to the Target Net. The only network whose weights we update via backpropagation is the Policy Net! And this is the one we use when we wish to test the model later. The idea is that by backpropagating on this difference the Policy Net will eventually learn to estimate both values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*cdGNzZdN3VKlKQwKLytv8A.png" /><figcaption>α is our Learning Rate and 𝛾 is the Discount Rate used to select the importante we give for the future values of <em>Q.</em></figcaption></figure><p>Reinforcement Learning is quite hard, so I’ll leave a bunch of links that will do a better job than I could ever do explaining all of this details. [<a href="https://www.analyticsvidhya.com/blog/2019/04/introduction-deep-q-learning-python/">1</a>][<a href="https://www.tensorflow.org/agents/tutorials/0_intro_rl">2</a>][<a href="https://pytorch.org/tutorials/intermediate/reinforcement_q_learning.html">3</a>]</p><h3>Training Procedure</h3><p>The training process was “bootstraped”, first I played the game myself, collected state and reward data, trained a shitty model and made it play Stardew Valley. I’ve written code so the game will continually generate new data, that I would then manually use to train new models on the Python side, generate a new ONNX artifact that the mod would reload every 1000 frames or so and then keep playing the game with new models and generating data to train newer ones. I’ve made it this way b̶e̶c̶a̶u̶s̶e̶ ̶I̶ ̶s̶u̶c̶k̶ ̶a̶t̶ ̶C̶# because since I had to compile the mod and pack it in a Windows DLL compatible with the game’s executable, I had some trouble finding a .NET Machine Learning framework that could generate the correct binaries (Stardew Valley is compiled in .NET 5), so I just gave up and coded this part in Python.</p><p>As you can see, one important insight that I had is that the model doesn’t <em>need</em> to be trained online. Q-learning is all about finding a good approximation of the function <em>Q(s,a)</em>, i.e. the function that estimates the value of performing a certain action <em>a</em> in a certain state <em>s</em>. The important thing is to make your data explore this state space thoroughly, it doesn’t matter that much whether you or the model played the game, although I will admit that it is way more impressive when the model does this on it’s own.</p><h3>Reading the ONNX model from C</h3><p>The only true ML code on the C# side is the ONNX runtime library, which defines a <strong>Tensor</strong> type and the session object that can send tensor inputs and collect tensor outputs from a serialized ONNX model. As you can see, the code is very self explanatory and straightforward. This <em>Update </em>function is run with every frame and queries the trained model for an action with the current state as input, these last lines are just some code to take the <em>argMax</em> of the model’s output, which is the index corresponding with the action that yielded the greater reward. I’m quite proud that the serialized model only weights about 120kb, so it is all very light to run.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d7836a5efb6d698a9d24b602ee5ca75/href">https://medium.com/media/1d7836a5efb6d698a9d24b602ee5ca75/href</a></iframe><h3>Using Harmony to HACK inputs into the game</h3><p>One thing that is missing from SMAPI is the ability to feed inputs in the game, and I think that 99.999% of the mods doesn’t need something like that. Mine did, so I found some code using a C# library called Harmony to change an internal function inside the game’s code in runtime so I could hack the game to think that it received a mouse input. This is what I use to let the mod play the game on it’s own. Huge thanks to <a href="https://github.com/Drynwynn">Drynwynn</a>, author of the mod FishingAutomaton, from which I used a lot of code to set up my mod.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/336436969f0b99ce650c6289ec05bf16/href">https://medium.com/media/336436969f0b99ce650c6289ec05bf16/href</a></iframe><h3>Final Results</h3><p>Currently, the model manages to catch all of the easy and “intermediate” fishes. I wasn’t yet able to train it to catch legendary fish.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*7h8xm3gmp4uRE-cq.gif" /><figcaption>Here is the model before any training.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*A1nOzbU4J3YvQ09O.gif" /><figcaption>Here is the model after thousands and thousands of iterations.</figcaption></figure><p>All the code both from the C# mod and the Python training can be found <a href="https://github.com/ThiagoLira/AutoFisher-SV">here</a>!</p><p>Huge thanks to the Stardew Valley’s modding community for the help in coding the mod and making me understand the game better :)</p><p>You can find the link for the Discord server <a href="https://stardewvalleywiki.com/Modding:Community">here</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4d0ebe77281" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Graphing citations between books using RoBERTa and D3.js]]></title>
            <link>https://thiago-lira.medium.com/graphing-citations-between-books-using-roberta-and-d3-js-1747360805ca?source=rss-afeea1f90ef6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1747360805ca</guid>
            <category><![CDATA[named-entity-recognition]]></category>
            <category><![CDATA[bert]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[literature]]></category>
            <dc:creator><![CDATA[Thiago Lira]]></dc:creator>
            <pubDate>Fri, 09 Apr 2021 20:42:18 GMT</pubDate>
            <atom:updated>2021-10-04T12:02:37.362Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E8TW7_tQLALSOzREAEaSvQ.png" /></figure><blockquote><em>Have you ever started thinking about all the relations between all the books you’ve read? If the authors of your favorite books have read one another, or even if they have read the same people from before their time? Which books then were read by basically everyone?</em></blockquote><p><strong>In this post I will share my pet-project of training a fine-tuned version of RoBERTa to detect citations in free-form (i.e. not just academic citations) between my books and generating a nice big directed graph with hundreds of books and their relations. All my Kindle library and more!</strong></p><h3>You can check the graph of citations made with my Kindle library and augmented with hundreds more books from Goodreads <a href="https://thiagolira.blot.im/_projects/book_graph/main.html">here</a>! (If possible play with the graph on a desktop because it sucks on mobile).</h3><p>Most of the code I’ll be going through on this post is avaliable <a href="https://github.com/ThiagoLira/BookGraph">here</a>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uvqjD9KPqtS_FRkXqhoqIQ.png" /><figcaption>D3.js force graph very elegantly displays the relations between my books.</figcaption></figure><h3>Citations in free-form?</h3><p>So, what am I calling citations in “free-form”? Well, anytime an author mentions another book on the text. For example, from Neil Gaiman’s <em>The View from the Cheap Seats</em>:</p><blockquote><em>“Children listened to them and enjoyed them, but children were not the primary audience, no more than they were the intended audience of </em>Beowulf<em>, or </em>The Odyssey<em>.”</em></blockquote><p>Why citations in “free-form”? Because bibliographical/academic citations are not present on older books and even on some new books. Depending on the type of book the author doesn’t need to construct a giant list of citations with precise bibliographical information at the end of the book. And with Deep Learning and enough data we might very well make a model that works on both kinds of citations and be done with it (At the end of the day it’s all text/data).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lPGaxNQTikFIjBjg6_V86w.jpeg" /><figcaption>Quote by Will Durant — <strong>Story of Western Philosophy</strong></figcaption></figure><h3>Why am I doing this?</h3><p>I love to read books about books, e.g. Will Durant’s <em>History of Western Philosophy</em> and Italo Calvino’s <em>Why Read the Classics</em> and I’m always curious to know the books that were formative on the lifes of my favorite authors (and on a bigger scale even society as a whole).</p><p>The idea was, then, to make <strong>something</strong> that would receive the text from some non-fiction book as input and output me all the books that are cited inside of it. Ideally the output from <em>Why Read The Classics</em> would be [‘The Odyssey’, ‘Candide’, ‘100 Years of Solitude’, …] and from <em>History of Western Philosophy</em> [“Basically everything ever written by a Greek, French or German guy (or gal) with way too much time on their hands”].</p><p>The process then would be to:</p><ol><li>Get the text from all my books.</li><li>Get metadata from all my books, authors, original publication date etc.(*)</li><li>Search on every book citations to every other book I have.</li><li>Build a rad looking graph illustrating all these citations with the books categorized by publication date.</li><li>EXTRA: Search for citations from my books to books I don’t own! (**)(***)</li></ol><p>(*) This was a somewhat convoluted process. It is hard to get the original publication date because this is sometimes something historical/uncertain, and there are dozens (or even hundreds!) of editions for many books. So I settled by importing all my books to Calibre and then using a <a href="https://www.mobileread.com/forums/showthread.php?t=130638">Goodreads plugin</a> to get the original publication date for each of them! Fun fact: It is pure pain and suffering to support very very distant dates with code (like b.c. dates).</p><p>(**) I did this by using a dataset scraped from Goodreads that has metadata from thousands of books, old and new. For my purposes I just filtered the dataset by removing books with no ratings/reviews and modern Fantasy/Fiction books that would pollute the analysis and probably are not cited many times (Which doesn’t mean that I don’t like Fantasy books, I LOVE Fantasy).</p><p>(***) <strong>Unfortunately, these extra citations are just one-way. I don’t have the text from these books to check which books they cite in turn. So… this part of the graph can only be the <em>target</em> of citations from the books I have!</strong></p><h3>The naive solution (and why this is more complicated than it seems)</h3><p>One simple solution is to build a list with a bunch of names of books and just search each title on the text of each book you own. And this actually works pretty well for most books (technical considerations on how to do this efficiently later). We start to have problems on smaller book titles like “The Prince” or “The Republic”, since this string of text might very well appear on a book with absolutely no relation to this particular work by Machiavelli. See the following example:</p><pre>&quot;The Prince reads Marcus Aurelius&#39; Meditations to relax.&quot; </pre><pre>&quot;Marcus Aurelius reads The Prince to relax.&quot;</pre><p>We can’t always expect that quotations in this form will be, well, <strong>quoted</strong> or in italics or whatever. So how to detect the string “The Prince” as a citation on the latter sentence but not on the former? There are many ways to go about this, and after iterating for a while I’ve settled on a NLP technique called NER, or <strong>named entity recognition</strong>.</p><h3>Creating a NER dataset for the task</h3><p>NER models should consume some text and then return the location of <em>labels</em> for each word.</p><p>The model has to be trained on some specific set of labels using some text with the annotations made beforehand. On my case we have a single label, <em>[BOOK]</em>. The relevant information are the indexes of the string where this tagged text begins and ends. NER models works by basically having a tag associated with each word (‘no-tag’ is also a tag!) and sequentially assigning a probability for each word on the text for being represented by each tag on the training data e.g. [“The Prince”: (0.8, ‘BOOK’ , 0.2, ‘NO_TAG’ ) , “Marcus Aurelius”: (0.1 , ‘BOOK’ , 0.9 , ‘NO_TAG’)].</p><p>Of course, I had to manually annotate a full dataset (a thousand examples!) of labels so that the model could learn what <em>is</em> and what <em>isn’t</em> a book, by context. It’s quite magical really when you see it working. Here are some examples from my dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f8dbd4512063d2498c45c1b8e9b5e24/href">https://medium.com/media/7f8dbd4512063d2498c45c1b8e9b5e24/href</a></iframe><p>To create my dataset I’ve searched on all my books for some ambiguous book titles such as “Ulysses” (The character from The Odyssey or the book from James Joyce?), “The Prince” (The book from Machiavelli or literally just some prince being referenced?) and “The Republic” (Plato’s book or… you get the idea). Then, I used <a href="https://github.com/doccano/doccano">Doccano</a> to manually annotate each passage from my books to tell if they are a citation or not.</p><h3>About Augumenting the Dataset</h3><p>After some failed attempts to make my models work well with new validation data, I started to <strong>augment</strong> my training dataset by swapping book titles around and creating new training examples. With some probability for each training example the code will swap the citation on some example with another random book title from my dataset and store this as a new training example (while still keeping the old one on the dataset).</p><p>Doing this has dramatically improved my model’s performance on validation data. Before this augmentation my model was overfitting on only labeling books if there were many examples with this specific book on my dataset. This was probably happening because (for Deep Learning standards) my ~1000 annotations dataset is quite small.</p><h3>Fine-Tuning RoBERTa</h3><p>Huggingface’s transformers library makes it child’s play to download a SOTA model and then fine-tune it on a specific task. You can even load a model with new layers initialized specifically to be fine-tuned on a new task, for this project, for a NER task, the transformers library provides a simple <strong>RobertaForTokenClassification </strong>class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cd74f01f2c37ccd98cee216e452097d/href">https://medium.com/media/2cd74f01f2c37ccd98cee216e452097d/href</a></iframe><p>The hardest part was to convert my annotations from Doccano’s format to something Pytorch would understand, and I thoroughly copied the code from <a href="https://gist.github.com/ThiagoLira/ff3e39c08db57d0a50bb7bef245c51d0">here</a> for that. And of course, to play with the hyper-parameters until the training yields good results. There are lots of things going on on this part, so I’m just gonna link my Notebook to fine-tune RoBERTa <a href="https://github.com/ThiagoLira/BookGraph/blob/main/FineTuneRobertaNER.ipynb">here</a>.</p><p>Finally, here are some test strings and the outputs from my model after fine-tuning! Look at this beautiful citations being automatically detected.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c2415d42428bb9156308ea8327727bc/href">https://medium.com/media/9c2415d42428bb9156308ea8327727bc/href</a></iframe><h3>Gluing all this together</h3><p>So far I’ve written about collecting the dataset, annotating and preprocessing it and finally, fine-tuning RoBERTa.</p><p>Now, how to actually process the text from all my books. The “algorithm” I wrote goes something like that:</p><ol><li>Load all books as lists of strings in memory.</li><li>For each line use a regex (+) to detected any book titles.</li><li>If the title detected is too short (e.g. less than 3 words)(*) run the whole line through RoBERTa and see if the NER model “validates” the title as a book title.</li><li>For each match pull it’s metadata and create a new node on the graph (if needed) and add a link between the book whose text we are currently reading and the book that was cited.</li><li>Convert this graph to D3.js format, add some metadata for each book and save it.</li></ol><p>(+) I ended up using a giant pre-compiled regex of the form r”Book1 | Book2 …” to look for matches because it was the fastest method I found. More on this on this <a href="https://stackoverflow.com/questions/42742810/speed-up-millions-of-regex-replacements-in-python-3">StackOverflow answer</a>.</p><p>(*) I choose this heuristic because I’m assuming that if longer titles like “The Hound of Baskerville” or “The Ballad of Reading Gaol” shows up on some book’s text it has a VERY high probability of being a citation, so I don’t need to waste CPU clocks confirming that with RoBERTa.</p><h3>How to take less than 8 hours to process all by books with RoBERTa</h3><p>By using multiprocessing! My book processing function receives as argument the list of lines from a book, it’s metadata and my model and tokenizer to parse the text. By creating a Pool of workers we can give each of them a book at a time to process asynchronously, when one worker finishes a book it starts processing another from the list. Just don’t overdo it since each RoBERTa takes ~1GB of RAM!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6536600e638e35c6b767c3087890a1b/href">https://medium.com/media/f6536600e638e35c6b767c3087890a1b/href</a></iframe><h3>Graph-ing everything up!</h3><p>The graph is built with <a href="https://networkx.org/">networkx</a> on the python side of the code, just so I could plot it and run the PageRank algorithm to see which books are the most “linked” on my data. Turns out it’s The Prince!</p><pre>[(‘The Prince’, 0.01081877301303925),<br> (‘Hamlet’, 0.01061937268317937),<br> (‘The Divine Comedy’, 0.007740738803800382),<br> (‘The Art of War’, 0.006072207782683749),<br> (‘Romeo and Juliet’, 0.0051880591489493295),<br> (‘Phaedrus’, 0.004890520471208026),<br> (‘Poetics’, 0.003865239838704173),<br> (‘Alice in Wonderland’, 0.0037039373900383415)]</pre><p>We just need some simple code to create a JSON with all this links and nodes and load it on D3.js. Here is the format of each node and each link on the final graph. One thing to note is the metadata we can save on each node to use it on the javascript side of the code later.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b0830ab8fdf101152caf030cf7741e0/href">https://medium.com/media/1b0830ab8fdf101152caf030cf7741e0/href</a></iframe><h3>Again, you can see the end result <a href="https://thiagolira.blot.im/_projects/book_graph/main.html">here</a>!</h3><h3>Some closing remarks</h3><p>Just some notes that might be useful to someone working with a similar problem:</p><ol><li>I’ve never increased my performance dramatically by toying with RoBERTa’s fine-tuning hyper-parameters. <strong>After you choose something that converges</strong> and are still unsatisfied, I’ll wager that by getting more/better data, or augumenting it like I did, you will get more substancial gains in performance.</li><li>Something that wasn’t obvious to me was that when you are using multiprocessing you <em>should</em> get close to 100% CPU use if you want your code to be running the fastest it possibly can (in retrospect it sounds kinda obvious now). If it is not close to 100% this probably means that your code is doing I/O or some processes are stuck (or deadlocked!) on something and can’t proceed with the computation, or you could spawn more processes to speed everything up.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1747360805ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[About the best books I've read on 2019]]></title>
            <link>https://thiago-lira.medium.com/about-the-best-books-ive-read-on-2019-321ac363bae4?source=rss-afeea1f90ef6------2</link>
            <guid isPermaLink="false">https://medium.com/p/321ac363bae4</guid>
            <category><![CDATA[bach]]></category>
            <category><![CDATA[books]]></category>
            <category><![CDATA[fantasy]]></category>
            <category><![CDATA[poetry]]></category>
            <category><![CDATA[shakespeare]]></category>
            <dc:creator><![CDATA[Thiago Lira]]></dc:creator>
            <pubDate>Tue, 07 Jan 2020 17:38:20 GMT</pubDate>
            <atom:updated>2020-01-07T17:42:13.632Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nRL5pp0IyiKBYCsq.jpg" /></figure><h3>I’ve had a lot of free time in 2019 and so I managed to read 50 books or so by the end of the year. Here are short reviews of the ones that impacted me the most. From Shakespeare plays, Sci-fi and Biographies to Fantasy.</h3><p><strong>Evening in the Palace of Reason (James R. Gaines)</strong>: Brilliant and informative, this book uses the famous meeting of Young King Frederick the Great of Prussia and Old Bach (THE Bach) to illustrate the whole ethos of an age of change (aren’t all ages a conflict between the Old and the New?). The enlighted “philosopher-king” gives the old-fashioned master, arguably the brightest genius of western civilization, a musical challenge. A challenge of improvisation and counterpoint, the old ways of music that were being slowly substituted by what we call today the Classical style (That itself was superseded by the Romantic style).</p><p><strong>De Profundis (Oscar Wilde):</strong> When Oscar Wilde was arrested on charges of “sodomy” and “gross indecency”. After a year of forced and miserable work, he was permitted to write as part of his rehabilitation by the prison warden. The product is a profound and somber letter of acceptance of one’s fate. He spends some words forgiving everyone involved in his incarceration and focuses on the healing of his own soul, the only way of doing that being accepting his fault and owning his mistakes on his exaggerated and hedonistic lifestyle. For one should be the only responsible for his own ruin (His words).</p><p><strong>Sixty Short Stories (Dino Buzzati):</strong> Curious short stories, on which the characters are often exposed to surreal situations that begs some meaning, but there isn’t one to be found, this is not the point. We only are told how they react and try make sense of the world around them, dealing with their own expectations.</p><p><strong>Lingua Latina: Per se Illustratta (Hans Ørberg):</strong> Hands down the best language learning book I’ve ever come across. I’ve given myself the challenge to learn Latin and I would have given up if not for this book’s didactic and fun approach of naturally introducing grammar on increasingly complex short stories, with new words being organically presented and recalled.</p><p><strong>Zeno’s Conscience (Italo Svevo):</strong> An old man (Zeno) recounts his life to his therapist, so that he may cure his lifelong psychological “disease” Zeno always believed he had. The book consists of the writings of episodes of his life that Zeno sent his doctor, before giving up on a cure. This is a book about the impossibility of pinning down one’s consciousness, about the randomness of life, of logically being cured of something that might very well be the disease of adapting to a messed up society.</p><p><strong>Hyperion (Dan Simmons):</strong> Beautiful beyond measure, this book tells the story of six pilgrims selected to travel to the outback of human civilization, to the planet Hyperion. Each one of them having had his life mysteriously affected by a entity known as the Shrike, a godlike being from another time that haunts human civilization and is linked with the artifact know as the Time Tombs on Hyperion. This jaw-dropping epic was inspired by Keats unfinished poem with the same name. The prose is musical and poetical at times, and the richness and beauty manages to inspire like few fiction books even dares to try. The planets of the human civilization have forests with trees bigger than anything society has ever built, seas of grass the size of an ocean, electrical jungles made of “Tesla Trees” and many more bizarre and beautiful vistas. This epic, like the poem that inspired it, is about surviving the creation of our own gods.</p><p><strong>A Mathematicians Apology (G.H. Hardy):</strong> A sincere memoir from one brilliant mathematician, G.H. Hardy. It demystified to me how does one works with Math. The search for patterns, for simplicity and at the end of the day, for beauty. This book gives a glimpse as to why some practitioners of the field see their activity as a craft or even an art form.</p><p><strong>The Name of the Rose (Umberto Eco):</strong> An expertly crafted historical detective-esque adventure set in medieval Italy. A mystery involving patterns of language and an exploration of theology and faith. A conflict on the physical level but also at the intellectual. A clash of philosophies presented with brilliant historical accuracy and infinitely packed with references and secrets on many levels of interpretation.</p><p><strong>Exhalation: Stories (Ted Chiang):</strong> Infinitely creative and though-provoking stories that contains these real and at times bizarre hypothetical worlds of possibility. In these worlds abstract problems of philosophy, language, religion, ethics, and physics are a tangible reality and this challenges the reader to think about our humanity in an expanded context. What if, on a world where the reality of the New Testament is proved beyond faith, scientists discover that the universe revolves around <em>other</em> planet and other people, the ones truly intended by divine design and not a random byproduct of evolution?This is one of the realities Chiang creates to bring to life new ways of thinking about old problems.</p><p><strong>Hamlet (Shakespeare):</strong> On the theme of Fate that I explored before on the list on ‘De Profundis’, this play is the ultimate existential exploration of one’s fate/duty. “To be or not to be” is a cliche today exactly because of the lasting impact it had on our culture. A little bit of Hamlet is inside many, if not most, of all tragic heroes since then.</p><p><strong>The Dresden Files (Jim Butcher)</strong> (I’ve read a bunch of books from series this year so I will just talk about what the series represents to me): There is something deeply human about the Dresden Files series. Harry Dresden is a character that has acknowledged fear, weakness, pain and regret as few people do. This mixture of bravado when the situation is incredibly dire and hopeless and the full knowledge that he <strong>is not</strong> prepared as he should be, and very well may die on this very day makes for a very relatable story to read. Again and again Harry is beaten, hurt physically and psychologically, kidnapped and threatened and yet, he soldiers on, barely capable of thinking straight or walking at times. He is so focused on his task because he knows that no one can do his job for him, that people depend on him, that he can only count on himself. He is incredibly stubborn on this regard, rarely trusts and even more rarely asks for help. Maybe he considers his task of saving people his bane on this earth. He plans two suicide missions on the same day (this happened on two books!), when he doesn’t even know if he will be alive to die on the second one. Lots of books and stories function like that with it’s heroes, but what helps making Harry’s adventure such an empathetic one is the First-Person narrative style of the books. It makes the experience evenintimate. Harry might act tough around enemies and friends alike but deep inside in his thoughts we have a glimpse at how vulnerable hereally feels.</p><p>I will concede that the books sometimes work like a male power fantasy and that might set some people off them. But there is a self-aware quality about the themes on the book: The author is clearly very passionate about the characters and the story and he clearly owns using some famous detective tropes with honesty. The main character considers himself a chauvinistic pig and chuckles about making grand entrances and saying corny one-liners. I think this is something lots of books and movies and games could learn something from on these cynical times.</p><p><strong>Kafka on the Shore (Haruki Murakami):</strong> This is a tough book to write about. Murakami magical realist style blurs the line between dream and reality. Nonsensical stuff happens all the time, charged with meaning but a the same time very elusive, as if you are always on the edge of understanding the big picture of all the bizarre and magical things driving the plot and the characters forward, like inside a dream. Even the characters themselves discuss about how everything might represent something else. I think Italo Calvino explains very well the power of metaphor can have in a book:</p><p>“I would say that the moment an object appears in a narrative, it is charged with a special force and becomes like the pole of a magnetic field, a knot in the network of invisible relationships. The symbolism of an object may be more or less explicit, but it is always there <em>We might even say that in a narrative any object is always magic.”</em> (Emphasis is mine)</p><p>And is this mystical setting where things are linked by metaphorical threads there isn’t anything the book is too afraid to deal with. The main character is on a quest of sexual discovery and finding his authenticity. He thinks himself cursed by his father to live something like Oedipus fate. Other characters are also cursed with different psychological realities, like one woman frozen in time. The physical and the mental realities intertwine is this amazing exploration of the human mind.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=321ac363bae4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using GPT-2 to generate Pokémon anime episodes]]></title>
            <link>https://medium.com/data-science/using-gpt-2-to-generate-pok%C3%A9mon-anime-episodes-113c0f15859c?source=rss-afeea1f90ef6------2</link>
            <guid isPermaLink="false">https://medium.com/p/113c0f15859c</guid>
            <category><![CDATA[gpt-2]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pokemon]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Thiago Lira]]></dc:creator>
            <pubDate>Tue, 05 Nov 2019 04:51:52 GMT</pubDate>
            <atom:updated>2019-11-05T04:51:52.437Z</atom:updated>
            <content:encoded><![CDATA[<p>A journey from data acquisition to hosting a web-service for something truly goofy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*quBsE9gao2WnT-to-d4Azw.gif" /></figure><blockquote>Ludicolo was a salsa master, he would teach Ash how to move like a god. He would make fun of Ash for being unable to move so quickly, and would even attack him for being weak.</blockquote><p>What follows is the story of someone using a ridiculously complex piece of technology just to make something goofy. The GPT-2 model, presented by OpenAI, was a game changer in AI generated text. So much so that the team behind the development of the model delayed it’s public release so people could prepare for a world were things like fake news could be generated effortlessly and without much human intervention. And YEAH today I’m going to show how one could use this dangerous artifact to create Pokémon episodes.</p><p><strong>You can check the end result here: </strong><a href="http://pokegen.thiagolira.com.br/"><strong>http://pokegen.thiagolira.com.br/</strong></a><strong> and all the code can be found on my </strong><a href="https://github.com/ThiagoLira/pkm-ep-generator"><strong>Github </strong></a><strong>repository. If you just want to see some examples skip to the end of the post.</strong></p><p>I can’t promise the website will answer all requests at all times because the server can’t deal with more than 3 requests at the same time (I will explain why shortly) and I’m already out of the free-tier to host it on AWS. But if the site yields an error, just wait some seconds and try again :)</p><p>In this article, I’ll try my best to explain the main challenges of an end-to-end machine learning project, every step of the way.</p><h3>The Data</h3><p><strong>Machine Learning methods are used to extract information and infer patterns from data.</strong> While classical statistical methods would have many parameters and assumptions selected by the statistician on the modeling phase, Machine Learning ones let the data speak for itself.<strong> This is a well known trade off between explainable (classical) models and accurate (machine learning) ones</strong>. The predictive power of machine learning basically comes from having a lot of data and a complex enough model to capture highly subtle patterns from it. There is a “smoothness” assumption that the model is being trained on a big enough sample of reality to infer (generalize) on what it doesn’t see directly, assuming it to be close to some example it has indeed been trained with (hence the smoothness).</p><p>Recent NLP (Natural Language Processing) models are no different and they need huge amounts of text and computing power to be trained. These new models start with zero knowledge of language and in the end, they become really good at gauging contextual information from sequences of words. To the point of understanding that the very same words have different meaning on different places on a sentence, something that classical NLP models are just not very good at achieving.</p><p>The GPT-2 model comes pre-trained on the entirety of Wikipedia, Reddit, and many other places. <strong>What I’ve done is to fine-tune the model on a more specific set of texts from the internet</strong>. This being the subset of the internet which consists of summaries of Pokémon anime episodes (and is on Bulbapedia). Shout out to <a href="https://bulbapedia.bulbagarden.net/">Bulbapedia</a> for being an excellent community-driven Pokémon website!</p><p>The crawler I wrote downloads around 400 episode summaries written by the community. Here is a sample from one episode:</p><blockquote><em>Ash declares to himself and the Pokémon of the world that he will become a Pokémon Master. His speech, however, is interrupted by his mom who tells him to get to bed as he has a big day tomorrow. Ash protests that he’s too excited to sleep, so his mom tells him that if he won’t sleep then to at least get ready for the next day as she switches on a program hosted by the town’s Pokémon expert, Professor Oak. Ash watches as Oak explains that new Trainers get to pick one of three Pokémon to start their journey; the Grass-type Bulbasaur, the Fire-type Charmander or the Water-type Squirtle.</em></blockquote><p>My crawler is on the file crawler_bulbapedia.py, and when run, will create a folder called data/pokeCorpusBulba where it will store every episode inside a separate text file.</p><p><strong>The data is not yet ready to be given to the model.</strong> Another script by the name prepare_corpus.py will clean the text and join them all in a single file called train.txt, ready to be used with GPT-2.</p><h3>The Model</h3><p>GPT-2 is a Transformer based model, that uses a technique called self-attention to learn in an astoundingly natural way how words would complete or continue sentences. I don’t think I can do a better job at explaining the mathematics and inner-workings of this model than these <a href="https://medium.com/inside-machine-learning/what-is-a-transformer-d07dd1fbec04">multiple</a> <a href="https://towardsdatascience.com/transformers-141e32e69591">excellent</a> <a href="https://towardsdatascience.com/openai-gpt-2-understanding-language-generation-through-visualization-8252f683b2f8">sources</a>. But I can offer some insights, on a purely programming perspective, on how to use this model pre-trained as if it were a text generating API. For that I’ve found an excellent resource, the <a href="https://github.com/minimaxir/gpt-2-simple">gpt-2-simple</a> python library, which makes all Tensorflow complexity basically invisible and offers some very simple functions to download, fine-tune and sample from the GPT-2 model.</p><p>Basically a language model tries to predict the next word from a sentence, and we can keep getting predictions from the model to generate new text, feeding the last predictions as new inputs to get more and more words. So as an example we can give our model the prefix input of “Ash and Pikachu were”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QBqFG_Kty5bRGApu-_GVHw.png" /></figure><p>What GPT-2 does, using an <strong>attention</strong> mechanism, is to dynamically assess the importance of the last words on predicting the next word. There is something called a “transformer cell” inside the model that calculates an attention value for each word on the input sequence in relation to every other word. This is all passed along to generate an output i.e. to predict the next word on the sentence.</p><p>As a somewhat simplified example, we can see by the strength of the attention values (the purple-er the more attention) that clearly “Ash” and “Pikachu” are relevant to determine what comes after “were”. This is something pretty nice about this model that classical “counting words” methods such as Naive-Bayes couldn’t do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OyQTYx8nUVVj8hoHIULx7w.png" /></figure><p><strong>The training occurs by blanking words on sentences from the corpus and fine-tuning the model to predict them correctly.</strong> <a href="https://www.youtube.com/watch?v=DlkpbzXjuPM">In the end</a>, we have a checkpoint folder, which is the only thing we need to generate text from this model. This folder created by tensorflow contains the whole state of the model after fine-tuning with my Pokémon corpus, and the gpt-2-simple library will look for it when generating new text.</p><h3>The server</h3><p>This was BY FAR the most challenging part. Serving this model for inference on the internet is not a trivial task since the text generation is so memory-heavy.</p><p><strong>Basically the server structure answers a GET request pointed at port 5000. It has a single function to answer this request that gets the parameters (the user input), initializes the model, generates some fixed amount of text, and returns everything inside a JSON.</strong> The difficult part is that the model occupies a whopping 1GB of memory to make an inference. So before anything I had to have a server with a decent amount of RAM (Goodbye AWS free tier! Twas’ nice meeting you). So I ended up choosing a EC2 t2-medium instance on AWS, and set it up with the good help of my friend <a href="https://github.com/jplippi">João</a>.</p><p>The following web-server structure to go inside the EC2 instance has been thoroughly copied from my other friend Gabriela, from her popular medium <a href="https://medium.com/@gabimelo/developing-a-flask-api-in-a-docker-container-with-uwsgi-and-nginx-e089e43ed90e">post</a>.</p><p>The web-server I chose to run on this EC2 instance is nginx, which listen for requests and then forwards them to a uWSGI web-server that communicates with the Flask app via the WSGI protocol. Basically we have this structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L4pBJuaK9ys3jtghyFJ1yw.png" /><figcaption>Diagram by<a href="https://medium.com/@gabimelo"> Gabriela Melo</a></figcaption></figure><p><strong>The WSGI protocol has the purpose of creating a common interface for web applications written in Python.</strong> So I, for example, could change the application framework (Flask to Django) or the application server (uWSGI to Unicorn) with this being essentially invisible to the other part.</p><p>Now, why I don’t just serve the uWSGI server to the web? Why use another layer, i.e. nginx? Well, the simple answer is that nginx abstracts away some issues that could come with server load, which uWSGI alone is unsuited to deal with.</p><p>I, of course, had to pack all this software on a Docker container, because that’s just how all the cool kids are doing nowadays. All the code is available on my <a href="https://github.com/ThiagoLira/pkm-ep-generator">Github</a> repository, but to read a really in-depth and well-made explanation of this configuration I suggest paying a visit to Gabriela’s <a href="https://medium.com/@gabimelo/developing-a-flask-api-in-a-docker-container-with-uwsgi-and-nginx-e089e43ed90e">post</a>, since my setup is basically the same, with some small tweaks because my application is a bit different.</p><h3>The Flask App</h3><p>The Flask App — the place where the model is run on the server — has a single entry-point for requests, the generate function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6615421d15eaf769fa55c3f66e890342/href">https://medium.com/media/6615421d15eaf769fa55c3f66e890342/href</a></iframe><h3>Lessons Learned</h3><ul><li>Data is very important if you want to make something new with Machine Learning. And cleaning it decently is just as important.</li><li><strong>The GPT-2 model is just impractical to use as an on-demand text generating tool, it needs too much memory and CPU power to run. It is very expensive to have a service that needs 1GB of RAM to serve each request.</strong></li><li><em>docker system prune </em>is your friend.</li><li>The Python ecosystem of web-servers is not that hard to use, and there are plenty of examples out there.</li></ul><h3>Some output examples</h3><p>The input feed to the model is in <strong>bold</strong>. Of course, there was some cherrypicking involved but this is just how generative models are.</p><blockquote><strong>Ash and Misty were dating when they fell in love.</strong> As they both recall their respective first experiences, ash’s first brush with pokémon is all he ever remembers, as he was just a child. later, after ash had made his first poké ball, he skipped lunch and pursued a friend and switched trainers. This ended in them both falling in love, leaving dawn and brock in tears. When they were out searching for ash’s bulbasaur, a wild gyarados swatted them off. (…)</blockquote><blockquote><strong>Pikachu was tired of all this sh*t.</strong> He runs in fear of the grass, and runs in fear of the trainers, too. Jessie and james run outside and run outside. (…)</blockquote><blockquote><strong>Ash wanted to be the very best and </strong>trained all of his pokémon to get there. He told his trainer the whole story and promised to be a great trainer. He told his parents and his friends that he would train them as best he could. They were surprised and were ready to give up on him, when his parents started crying. His mother told him to come back home and find his friends. They had no choice but to go with him.</blockquote><blockquote><strong>Pikachu was being arrested for tax evasion.</strong> Once the trio get out of the olivine city pokémon center, they are immediately attacked by a former police officer, a police detective, a nurse joy, and a nurse joy’s glameow.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=113c0f15859c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/using-gpt-2-to-generate-pok%C3%A9mon-anime-episodes-113c0f15859c">Using GPT-2 to generate Pokémon anime episodes</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>