<?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 Vitou Phy on Medium]]></title>
        <description><![CDATA[Stories by Vitou Phy on Medium]]></description>
        <link>https://medium.com/@phyvitou?source=rss-81157f79faae------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZE3q_EFE0Od84MI1m6NPiw@2x.jpeg</url>
            <title>Stories by Vitou Phy on Medium</title>
            <link>https://medium.com/@phyvitou?source=rss-81157f79faae------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 20:24:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@phyvitou/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[Informal Explanation on Shannon Entropy]]></title>
            <link>https://medium.com/@phyvitou/informal-explanation-on-shannon-entropy-af70132ce605?source=rss-81157f79faae------2</link>
            <guid isPermaLink="false">https://medium.com/p/af70132ce605</guid>
            <category><![CDATA[information-theory]]></category>
            <category><![CDATA[entropy]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Vitou Phy]]></dc:creator>
            <pubDate>Tue, 05 Jul 2022 05:02:26 GMT</pubDate>
            <atom:updated>2022-07-05T05:02:26.195Z</atom:updated>
            <content:encoded><![CDATA[<h4>Information theory on Entropy as a measurement of uncertainty</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EGLZLcYyx1-h9K_zDcDW1w.png" /><figcaption>Image generated by OpenAI’s Dall-E with prompt “painting of coin toss in the sky”</figcaption></figure><p>The term entropy has been used across different fields such as physics, information theory, and cyber security. In information theory, I often find many articles using definitions as follows:</p><ul><li>Entropy refers degree of randomness or</li><li>Entropy is the <em>expected</em> number of bits of information contained in each message, taken over all possibilities for the transmitted message.</li><li>Entropy is an average level of “information”, “surprise”, or “uncertainty” of a variable’s possible outcomes.</li></ul><p>Having so various forms of explanation are somewhat tricky to understand, and it’s even more so if we mix them together. For this article, we pick one definition and run with it. And that is seeing entropy in terms of measurement for uncertainty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*3oUfRnK4DldeiFyncyb1OQ.png" /><figcaption>Entropy Formula</figcaption></figure><p>Essentially, entropy is an average (expected value) of information or uncertainty of a random variable. Let’s break this down and focus on the information I(x).</p><h3>Shannon Information I(x)</h3><p>Informally, let’s say we want to have a function to measure uncertainty. We notice that generally high probability is the same as low uncertainty, and low probability is the same as high uncertainty. When you are 99% sure that it’s gonna rain, that’s super-low uncertainty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*rTK4EDsb1GGPkgJ-xsIOvw.png" /><figcaption>Shannon Information</figcaption></figure><p>Fortunately, these log operations give us just that. It’s able to convert a probability of 1.0 to 0 uncertainty and a probability of 0 to a high number of uncertainty. In other words, we can think of this information I(X) as a simple non-linear transformation function to measure uncertainty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*DRHwXTJxE72kNP_AyYPIEg.png" /><figcaption>Get number of outcome from bits</figcaption></figure><p>What else can we think of this uncertainty? Suppose an image can be of 4 animals. For a case where an ML model says that an image has 50% being a cat. This is equivalent to log2(0.5) = <strong>1 bit</strong> of uncertainty. What this means is that although we have 4 possible animals, the chance of an image being a cat is the same as the chance of flipping a coin and getting a head. Notice that <strong>one bit of uncertainty</strong> is compared with <strong>flipping one coin</strong>. Alternatively, we roughly have 2^(1 bit)=2 possible choices to choose from.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6tQZ5v1sjyl81AZq8Nmb5A.png" /><figcaption>Image generated by OpenAI’s Dall-E with prompt “painting of a dog that looks like a cat”</figcaption></figure><p>Similarly, suppose that image now has 1.25% of being a cat, that would be log2(0.125) = <strong>3 bits</strong> of uncertainty. This suggests that this image is as uncertain as tossing <strong>a coin 3 three times</strong> and getting all heads, or simply 2^(3 bits)=8 possible choices to pick from. So, we can say that this <strong>bit unit</strong> <strong>tells us the odds of an event as if we are comparing the chance of a coin toss</strong>.</p><h3>Entropy</h3><p>Let’s move on to entropy. Entropy is an average of uncertainty across all events of a random variable. Informally, it tells how uncertain a random variable is. Is it as random tossing a coin, two coins, or n coins?</p><p>Let’s denote the animals earlier as random variable X that can have 4 possible outcomes such as cat, dog, mouse, and bird. Suppose we make a prediction on an image and the model says that the chance of being any animal is equally 0.25. In this case, the average of uncertainty (entropy) is 2 bits, meaning the odd is the same as tossing the coin two times and getting all heads. Or we have 2² choices to choose from.</p><p>You’d be like, duh! Obvious much. But let’s see the next example.</p><p>Instead, let’s say a cat has a chance of 90%, a dog has 4%, and a mouse and bird have 3% each. We would have the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*ixPJTpDpQr_RdJzP3y87dw.png" /><figcaption>Calculate entropy across all possible events (type of animals)</figcaption></figure><p>The average uncertainty (entropy) of variable X is 0.63 bit, which is less than just tossing a coin (1 bit). Normally, we would have 4 possible outcomes (4 types of animals) to choose from. But if we apply the rule of this bit, we would have 2⁰.63 = 1.54 outcomes. This implies that because we have a 90% chance of getting a cat, we may not deal with 4 choices anymore. It’s as if we now have 1.54 choices to choose from. And that’s what the entropy is for, which is to tell us how uncertain a random variable is. Is it as random as tossing 1 coin or 3 coins?</p><h3>Conclusion</h3><p>To sum things up, there are many ways to explain entropy. In this article, we try to explain entropy that it’s an average uncertainty of a random variable. We know that the events themselves have a different chance of occurring. Entropy is just there to tell us how random it is as if we compare it to an odd of tossing some coins.</p><h3>Reference</h3><ul><li><a href="https://brilliant.org/wiki/entropy-information-theory/">https://brilliant.org/wiki/entropy-information-theory/</a></li><li><a href="https://brilliant.org/wiki/entropy-information-theory/">https://brilliant.org/wiki/entropy-information-theory/</a></li><li><a href="https://www.techtarget.com/whatis/definition/entropy">https://www.techtarget.com/whatis/definition/entropy</a></li><li><a href="https://en.wikipedia.org/wiki/Entropy_(information_theory)">https://en.wikipedia.org/wiki/Entropy_(information_theory)</a></li><li><a href="https://en.wikipedia.org/wiki/Information_content">https://en.wikipedia.org/wiki/Information_content</a></li><li><a href="https://towardsdatascience.com/the-intuition-behind-shannons-entropy-e74820fe9800">https://towardsdatascience.com/the-intuition-behind-shannons-entropy-e74820fe9800</a></li><li><a href="https://machinelearningmastery.com/what-is-information-entropy/">https://machinelearningmastery.com/what-is-information-entropy/</a></li><li><a href="https://www.khanacademy.org/computing/computer-science/informationtheory/moderninfotheory/v/information-entropy">https://www.khanacademy.org/computing/computer-science/informationtheory/moderninfotheory/v/information-entropy</a></li><li><a href="https://www.youtube.com/watch?v=v68zYyaEmEA&amp;t=330s&amp;ab_channel=3Blue1Brown">https://www.youtube.com/watch?v=v68zYyaEmEA&amp;t=330s&amp;ab_channel=3Blue1Brown</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af70132ce605" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Instability in Training Text-GAN]]></title>
            <link>https://medium.com/data-science/instability-in-training-text-gan-20273d6a859a?source=rss-81157f79faae------2</link>
            <guid isPermaLink="false">https://medium.com/p/20273d6a859a</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Vitou Phy]]></dc:creator>
            <pubDate>Mon, 17 Aug 2020 15:28:47 GMT</pubDate>
            <atom:updated>2020-08-17T15:28:47.526Z</atom:updated>
            <content:encoded><![CDATA[<h4>Plenty of Tinkering with Black-Box</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c4DrBDx5xfeQcj7u" /><figcaption>Photo by <a href="https://unsplash.com/@jamesponddotco?utm_source=medium&amp;utm_medium=referral">James Pond</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>In text generation, conventionally, maximum likelihood estimation is used to train a model to generate a text one token at a time. Each generated token will be compared against the ground-truth data. If any token is different from the actual token, this information will be used to update the model. However, such training may cause the generation to be generic or repetitive.</p><p>Generative Adversarial Network (GAN) tackles this problem by introducing 2 models — generator and discriminator. The goal of the discriminator is to determine whether a sentence x is real or fake (fake refers to generated by models), whereas the generator attempts to produce a sentence that can fool the discriminator. These two models are competing against each other, which results in the improvement of both networks until the generator can produce a human-like sentence.</p><p>Although we may see some promising results with computer vision and text generation communities, getting hands-on this type of modeling is difficult.</p><h3>Problem with GANS</h3><ol><li><strong>Mode Collapse (Lack of Diversity) </strong>This is a common problem with GAN training. Mode collapse occurs when the model does not care about the input random noise, and it keeps generating the same sentence regardless of the input. In this sense, the model is now trying to fool the discriminator, and finding a single point is sufficient enough to do so.</li><li><strong>Unstable Training. </strong>The most important problem is to ensure that the generator and the discriminator are on par to each other. If either one outperforms each other, the whole training will become unstable, and no useful information will be learned. For example, when the generator’s loss is slowly reducing, that means the generator starts to find a way to fool the discriminator even though the generation is still immature. On the other hand, when discriminator is OP, there is no new information for the generator to learn. Every generation will be evaluated as fake; therefore, the generator will have to rely on changing the word randomly in searching for a sentence that may fool the D.</li><li><strong>Intuition is NOT Enough</strong>. Sometimes, your intended modeling is correct, but it may not work as you want it to be. It may require more than that to work. Frequently, you need to do hyperparameters tuning by tweaking learning rate, trying different loss functions, using batch norm, or trying different activation functions.</li><li><strong>Lots of Training Time. </strong>Some work reported training up to 400 epochs. That is tremendous if we compare with Seq2Seq that might take only 50 epochs or so to get a well-structured generation. The reason that causes it to be slow is the exploration of the generation. G does not receive any explicit signal of which token is bad. Rather it receives for the whole generation. To able to produce a natural sentence, G needs to explore various combinations of words to reach there. How often do you think G can accidentally produce &lt;eos&gt; out of nowhere? If we use MLE, the signal is pretty clear that there should be &lt;eos&gt; and there are &lt;pad&gt; right after it.</li></ol><h3>Potential Solutions</h3><p>Many approaches have been attempted to handle this type of training.</p><ol><li><strong>Use ADAM Optimizer</strong>. Some suggest using the ADAM for the generator and SGD for the discriminator. But most importantly, some paper starts to tweak the beta for the ADAM. betas=(0.5, 0.999)</li><li><strong>Wasserstein GAN</strong>. Some work reports using WGAN can stabilize the training greatly. From our experiments, however, WGAN can not even reach the quality of regular GAN. Perhaps we are missing something. (See? It’s quite difficult)</li><li><strong>GAN Variation</strong>. Some suggest trying KL-GAN, or VAE-GAN. These can make the models easier to train.</li><li><strong>Input Noise to the Discriminator</strong>. To make the discriminator’s learning on par with the generator, which in general have a harder time than the D, we input some noise along with the input as well as using dropout to make things easier.</li><li><strong>DCGAN (Deep Convolutional GAN)</strong>. This is only for computer vision tasks. However, this model is known to avoid unstable training. The key in this model is to not use ReLU, use BatchNorm, and use Strided Convolution.</li><li><strong>Ensemble of Discriminator</strong>. Instead of having a single discriminator, multiple discriminators are trained with different batch, to capture different aspects of respect. Thus, the generator can not just fool a single D, but to be more generalized so that it can fool all of them. This is also related to Dropout GAN (many D and dropout some during training).</li><li><strong>Parameter Tuning</strong>. With the learning rate, dropout ratio, batch size, and so on. It is difficult to determine how much a model is better than another. Therefore, some would test on multiple parameters and see whichever works best. One bottleneck is there is no evaluation metric for GAN, which results in a lot of manual checks to determine the quality.</li><li><strong>Scheduling G and D</strong>. Trying to learn G 5 times followed by D 1 times are reported to be useless in many work. If you want to try scheduling, do something more meaningful.</li></ol><pre>while generator_loss &gt; 0.5:<br>    train_G()</pre><pre>while discriminator_loss &gt; 0.5:<br>    train_D()</pre><h3>Conclusion</h3><p>Adversarial-based text generation opens a new avenue on how a model is trained. Instead of relying on MLE, discriminator(s) are used to signal whether or not the generation is correct. However, such training has its downside that it is quite hard to train. Many studies suggest some tips on how to avoid the problems are described above; however, you need to try a variety of settings (or parameters) to assure your generative model can learn properly.</p><h3>Further Reading</h3><ul><li><a href="https://machinelearningmastery.com/practical-guide-to-gan-failure-modes/">How to Identify and Diagnose GAN Failure Modes - Machine Learning Mastery</a></li><li><a href="https://lilianweng.github.io/lil-log/2017/08/20/from-GAN-to-WGAN.html">From GAN to WGAN</a></li><li><a href="https://github.com/soumith/ganhacks">GitHub - soumith/ganhacks: starter from &quot;How to Train a GAN?&quot; at NIPS2016</a></li><li><a href="https://medium.com/@jonathan_hui/gan-why-it-is-so-hard-to-train-generative-advisory-networks-819a86b3750b">GAN — Why it is so hard to train Generative Adversarial Networks!</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20273d6a859a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/instability-in-training-text-gan-20273d6a859a">Instability in Training Text-GAN</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decoding Strategies that You Need to Know for Response Generation]]></title>
            <link>https://medium.com/data-science/decoding-strategies-that-you-need-to-know-for-response-generation-ba95ee0faadc?source=rss-81157f79faae------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba95ee0faadc</guid>
            <category><![CDATA[dialogue]]></category>
            <category><![CDATA[nlg]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[decoding]]></category>
            <category><![CDATA[generation]]></category>
            <dc:creator><![CDATA[Vitou Phy]]></dc:creator>
            <pubDate>Thu, 09 Jul 2020 03:01:10 GMT</pubDate>
            <atom:updated>2020-07-09T03:01:10.533Z</atom:updated>
            <content:encoded><![CDATA[<h4>Distinguish between Beam Search, Random Sampling, Top-K, and Nucleus</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qC-KFHQLToPASxawmUPWLQ.png" /><figcaption>Different Sampling Techniques. Note, we did not use strong generative model for this example.</figcaption></figure><h3>Introduction</h3><p>Deep learning has been deployed in many tasks in NLP, such as translation, image captioning, and dialogue systems. In machine translation, it is used to read source language (input) and generate the desired language (output). Similarly in a dialogue system, it is used to generate a response given a context. This is also known as Natural Language Generation (NLG).</p><p>The model splits into 2 parts: encoder and decoder. Encoder reads the input text and returns a vector representing that input. Then, the decoder takes that vector and generates a corresponding text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yef6QgRpT1ktP6BpHelPmA.png" /><figcaption>Figure 1: Encoder-Decoder Architecture</figcaption></figure><p>To generate a text, commonly it is done by generating one token at a time. Without proper techniques, the generated response may be very generic and boring. In this article, we will explore the following strategies:</p><ul><li>Greedy</li><li>Beam Search</li><li>Random Sampling</li><li>Temperature</li><li>Top-K Sampling</li><li>Nucleus Sampling</li></ul><h3>Decoding Strategies</h3><p>At each timestep during decoding, we take the vector (that holds the information from one step to another) and apply it with softmax function to convert it into an array of probability for each word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*an6EilLiOG0G4KwoE0vKYw.png" /><figcaption>Equation 1: Softmax Function. x is a token at timestep i. u is the vector that contains the value of every token in the vocabulary.</figcaption></figure><h4>Greedy Approach</h4><p>This approach is the simplest. At each time-step, it just chooses whichever token that is the most probable.</p><pre>Context:            Try this cake. I baked it myself.<br>Optimal Response  : This cake tastes great.<br>Generated Response: This is okay.</pre><p>However, this approach may generate a suboptimal response, as shown in the example above. The generated response may not be the best possible response. This is due to the training data that commonly have examples like “That is […]”. Therefore, if we generate the most probable token at a time, it might output “is” instead of “cake”.</p><h4>Beam Search</h4><p>Exhaustive search can solve the previous problem since it will search for the whole space. However, it would be computationally expensive. Suppose there are 10,000 vocabularies, to generate a sentence with the length of 10 tokens, it would be (10,000)¹⁰.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nx7Slea9lBDs6uEx7VQQRA.png" /><figcaption>Figure 2: Beam Search with BeamWidth=2 (<a href="https://d2l.ai/chapter_recurrent-modern/beam-search.html">Source</a>)</figcaption></figure><p>Beam search can cope with this problem. At each timestep, it generates all possible tokens in the vocabulary list; then, it will choose top B candidates that have the most probability. Those B candidates will move to the next time step, and the process repeats. In the end, there will only be B candidates. The search space is only (10,000)*B.</p><pre>Context:    Try this cake. I baked it myself.<br>Response A: That cake tastes great.<br>Response B: Thank you.</pre><p>But sometimes, it chooses an even more optimal (Response B). In this case, it makes perfect sense. But imagine that the model likes to play safe and keeps on generating “I don’t know” or “Thank you” to most of the context, that is a pretty bad bot.</p><h4>Random Sampling</h4><p>Alternatively, we can look into stochastic approaches to avoid the response being generic. We can utilize the probability of each token from the softmax function to generate the next token.</p><p>Suppose we are generating the first token of a context “I love watching movies”, Figure below shows the probability of what the first word should be.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G2KSr9AnmQP6VRnmbE6fbQ.png" /><figcaption>Figure 3: Probability of each word. X-axis is the token index. i.e, index 37 corresponds to the word “yeah”</figcaption></figure><p>If we use a greedy approach, a token “i” will be chosen. With random sampling, however, token <em>i</em><strong><em> </em></strong>has a probability of around 0.2 to occur. At the same time, any token that has a probability of 0.0001 can also occur. It’s just very unlikely.</p><h4>Random Sampling with Temperature</h4><p>Random sampling, by itself, could potentially generate a very random word by chance. Temperature is used to increase the probability of probable tokens while reducing the one that is not. Usually, the range is 0 &lt; temp ≤ 1. Note that when temp=1, there is no effect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*41TqaBXrhIGU2V1JCEzU5Q.png" /><figcaption>Equation 2: Random sampling with temperature. Temperature t is used to scale the value of each token before going into a softmax function</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i9cXkz-TWG7-BS6CycahuQ.png" /><figcaption>Figure 4: Random sampling vs. random sampling with temperature</figcaption></figure><p>In Figure 4, with temp=0.5, the most probable words like <em>i</em>, <em>yeah</em>, <em>me</em>, have more chance of being generated. At the same time, this also lowers the probability of the less probable ones, although this does not stop them from occurring.</p><h4>Top-K Sampling</h4><p>Top-K sampling is used to ensure that the less probable words should not have any chance at all. Only top K probable tokens should be considered for a generation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xszHiw9cXHZfXZkAzf2ixw.png" /><figcaption>Figure 5: Distribution of the 3 random sampling, random with temp, and top-k</figcaption></figure><p>The token index between 50 to 80 has some small probabilities if we use random sampling with temperature=0.5 or 1.0. With top-k sampling (K=10), those tokens have no chance of being generated. Note that we can also combine Top-K sampling with temperature, but you kinda get the idea already, so we choose not to discuss it here.</p><p>This sampling technique has been adopted in many recent generation tasks. Its performance is quite good. One limitation with this approach is the number of top K words need to be defined in the beginning. Suppose we choose K=300; however, at a decoding timestep, the model is sure that there should be 10 highly probable words. If we use Top-K, that means we will also consider the other 290 less probable words.</p><h4>Nucleus Sampling</h4><p>Nucleus sampling is similar to Top-K sampling. Instead of focusing on Top-K words, nucleus sampling focuses on the smallest possible sets of Top-V words such that the sum of their probability is ≥ p. Then, the tokens that are not in V^(p) are set to 0; the rest are re-scaled to ensure that they sum to 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uIM24H7IclafNGWmIaTZZw.png" /><figcaption>Equation 3: Nucleus sampling. V^(p) is the smallest possible of tokens. P(x|…) is the probability of generating token x given the previous generated tokens x from 1 to i-1</figcaption></figure><p>The intuition is that when the model is very certain on some tokens, the set of potential candidate tokens is small otherwise, there will be more potential candidate tokens.</p><blockquote><em>Certain → those few tokens have high probability = sum of few tokens is enough to exceed p.<br>Uncertain → Many tokens have small probability = sum of many tokens is needed to exceed p.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tjCJSAxvMa3HhisMl7D8Ug.png" /><figcaption>Figure 6: Distribution of Top-K and Nucleus Sampling</figcaption></figure><p>Comparing nucleus sampling (p=0.5) with top-K sampling (K = 10), we can see the nucleus does not consider token “you” to be a candidate. This shows that it can adapt to different cases and select different numbers of tokens, unlike Top-K sampling.</p><h3>Summary</h3><ul><li>Greedy: Select the best probable token at a time</li><li>Beam Search: Select the best probable response</li><li>Random Sampling: Random based on probability</li><li>Temperature: Shrink or enlarge probabilities</li><li>Top-K Sampling: Select top probable K tokens</li><li>Nucleus Sampling: Dynamically choose the number of K (sort of)</li></ul><p>Commonly, top choices by researchers are beam search, top-K sampling (with temperature), and nucleus sampling.</p><h3>Conclusion</h3><p>We have gone through a list of different ways to decode a response. These techniques can be applied to different generation tasks, i.e., image captioning, translation, and story generation. Using a good model with bad decoding strategies or a bad model with good decoding strategies is not enough. A good balance between the two can make the generation a lot more interesting.</p><h3>References</h3><p>Holtzman, A., Buys, J., Du, L., Forbes, M., &amp; Choi, Y. (2020). The Curious Case of Neural Text Degeneration. In <em>International Conference on Learning Representations</em>.</p><ul><li><a href="https://towardsdatascience.com/word-sequence-decoding-in-seq2seq-architectures-d102000344ad">Word Sequence Decoding in Seq2Seq Architectures</a></li><li><a href="https://towardsdatascience.com/an-intuitive-explanation-of-beam-search-9b1d744e7a0f">An intuitive explanation of Beam search</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba95ee0faadc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/decoding-strategies-that-you-need-to-know-for-response-generation-ba95ee0faadc">Decoding Strategies that You Need to Know for Response Generation</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Accuracy is NOT enough for Classification Task]]></title>
            <link>https://medium.com/data-science/accuracy-is-not-enough-for-classification-task-47fca7d6a8ec?source=rss-81157f79faae------2</link>
            <guid isPermaLink="false">https://medium.com/p/47fca7d6a8ec</guid>
            <category><![CDATA[evaluation-metric]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Vitou Phy]]></dc:creator>
            <pubDate>Mon, 09 Dec 2019 19:30:01 GMT</pubDate>
            <atom:updated>2019-12-11T12:52:24.541Z</atom:updated>
            <content:encoded><![CDATA[<h3>Accuracy is NOT enough for Classification Tasks</h3><h4>The difference between accuracy, precision and recall</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zISyUAH_W9jAu7rB" /><figcaption>Photo by <a href="https://unsplash.com/@matthewhenry?utm_source=medium&amp;utm_medium=referral">Matthew Henry</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this machine learning era, we’ve seen a lot of hypes on using AI to classify whether an image contains a puppy, to do spam detection or to train self-driving car to recognize traffic-sign. Just as having the right model is important, it is even more crucial to be able to tell how well your model performs so that you can choose the one that is well suited for your task.</p><p>In this post, we will go through:</p><ul><li>General definition of classification task</li><li>Accuracy metrics</li><li>Precision and recall</li><li>Confusion metrics</li><li>Precision-Recall tradeoff</li></ul><h3>What’s Classification?</h3><p>Suppose you are presented with an image above, the task is to decide if the image contains a dog or not. If you answer correctly, you get a point. If not, you will not get any. This is commonly known as classification task where you try to assign a specific label to a given data.</p><p>This classification task is quite popular in machine learning community that they try to train their model and see if the current algorithm can fully distinguish between the objects. For this article, we will not focus on which algorithm to use. Instead, we assume that we have an algorithm already and we want to know if our algorithm performs well or not?</p><h3>Accuracy</h3><p>One of the simple evaluation metrics is accuracy. Suppose you have 5 images and the model gets 4 of them right, then the score is 0.8. Thus, we can say accuracy is the number of correctly classified images over total images. That is simple and intuitive, but this is not enough.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*O2pd8O6Gg2iXDANTQqzVjw.png" /><figcaption>Figure 1 — Images of dog and not-dog</figcaption></figure><p>The accuracy itself has some downfall. Let’s consider the example below. Suppose our dataset has 5 images: 4 are not-dogs and 1 is a dog. Also we have an algorithm as the following:</p><pre>def is_a_dog (x):<br>    return False</pre><p>The naive algorithm above assumes everything is not a dog without doing any computation on the given data. One thing to notice is that because coincidentally our dataset has 4 images that are not-dog, such naive algorithm gets the score of 0.8 . That’s not what we want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*ebV818artycNctONc2o2AQ.png" /><figcaption>Figure 2 — Naive algorithm returns all False</figcaption></figure><h3>Precision and Recall</h3><p>2 concepts to combat such situation are precision and recall. Let’s look at their brief explanations below.</p><ul><li><strong>Precision</strong>: Among all of the predictions that are “dog”, how many of them are correctly classified?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tZDuAZxMobRZgR_FawAz_g.png" /></figure><ul><li><strong>Recall</strong>: Among all of data that are “dog”, how many of them are correctly classified?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BXvii9wAnBmmdzorxh8VkA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*WuBEcAN2qgyX-KHpKw_now.png" /><figcaption>Figure 3 — Recall (looks only on data whose labels are dogs)</figcaption></figure><p>Let’s start with recall. Among our dataset, there is only 1 dog and our algorithm classified that as not-dog. Therefore, recall=0/1=0.</p><p>Whereas for precision, among the predictions, none of them are even predicted as dog. Thus, precision=0/0. Note that in some case, division for precision is not possible due to denominator being 0; thus, we can simply assume precision=0 in this case.</p><h3>Confusion Matrix</h3><p>Confusion matrix split the data into 4 categories: true positive, true negative, false positive and false negative as shown in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*eZ6PaQ2dOp8Rkq6JzFAcWw.png" /><figcaption>Figure 4 — Confusion Matrix</figcaption></figure><ul><li>True positive is when the data has label “dog” and the prediction has the same positive label.</li><li>True negative is when the data’s label is “not-dog” and the prediction correctly has the same labels.</li><li>False positive is when the data’s label is “not-dog” but the algorithm misses classify it as “dog”.</li><li>False negative is when the data’s label is “dog”, but the algorithm says otherwise.</li></ul><p>Commonly, when we want to compute precision and recall, confusion matrix is used. The calculation is the same as described in the previous section but it makes the numbers more easy to read. For this example, we will look at a different case where we attempt to classify 10 images instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*3mzcmFwDILC6794OvHDluQ.png" /><figcaption>Figure 5 — Example of 10 images. Label underneath the images are the prediction</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GdNotNrNYQcOIZqDdEm4pQ.png" /><figcaption>Figure 6 — Confusion Matrix on 10 images</figcaption></figure><p>In this case, the precision is 4/(4+3)=0.57 whereas recall is 4/(4+2)=0.66.</p><h3>Precision or Recall</h3><p>Ideally, we want both values to be as high as possible. However, that might not be possible. As we increase recall, precision will decrease and vice versa. Therefore, we need to decide which one is more important for the task. Let’s take a closer look how this phenomenon can occur.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*xxCAkYj1j6LqOSDX3O68yg.png" /><figcaption>Figure 7 — PrecisionRecall Tradeoff</figcaption></figure><p>The green box are the correctly classified labels and the yellow box are the incorrectly classified labels. Each image that is misclassified must go into one of the yellow box: false positive (precision) or false negative (recall). It of course can not be in both.</p><p>Suppose our model will surely have 5 incorrect labels, if all the incorrect classifications fall into false-positive, then we will have low precision and high recall. However, if the incorrect labels fall into false-negative, we will instead have high precision and low recall.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jC6N5c55Wq0rSMk1oanUew.png" /><figcaption>Figure 8 — Examples of Precision-Recall Tradeoff</figcaption></figure><p>Therefore, when you train your machine learning model, you need to decide which metrics is more important. For instance, if you were asked to build a model for financial institution where they want classify whether the borrower is a good candidate or not, you may prefer your model not to give the loan recklessly. Therefore, you rather classify the good people as bad people (false negative) rather than to classify the bad people as good one (false positive).</p><p>In other word, false negative (recall) is more preferable the false positive (precision).</p><h3>Conclusion</h3><p>So, next time you are presented with a classification task, make sure not to just pick accuracy as metrics and jump into designing the model right away. Of course, playing around with the model is exciting but it’s important to take some time to have a clear picture of what kind of problems you are tackling and which metrics are most suitable for the task. Once you get that out of the way, you can be certain that your model you are building will be the right one for your task.</p><h3>Key Takeaway</h3><p>That’s it. We have reached the end of this article. Just to recap on what we just discussed, here are some key takeaways from the article:</p><ol><li>Accuracy is not enough for classification task. We need to look at some other metrics to make sure our model is reliable.</li><li>Precision: Among all of the predictions that says dog, how many of them are correctly classified?</li><li>Recall: Among all of data that says dog, how many of them are correctly classified?</li><li>Confusion matrix helps you analyze the performance of your model better.</li></ol><h3>References</h3><ul><li><a href="https://en.wikipedia.org/wiki/Precision_and_recall">https://en.wikipedia.org/wiki/Precision_and_recall</a></li><li><a href="https://machinelearningmastery.com/classification-accuracy-is-not-enough-more-performance-measures-you-can-use/">https://machinelearningmastery.com/classification-accuracy-is-not-enough-more-performance-measures-you-can-use/</a></li><li><a href="https://medium.com/techspace-usict/measuring-just-accuracy-is-not-enough-in-machine-learning-a-better-technique-is-required-e7199ac36856">https://medium.com/techspace-usict/measuring-just-accuracy-is-not-enough-in-machine-learning-a-better-technique-is-required-e7199ac36856</a></li><li><a href="https://towardsdatascience.com/beyond-accuracy-precision-and-recall-3da06bea9f6c">https://towardsdatascience.com/beyond-accuracy-precision-and-recall-3da06bea9f6c</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47fca7d6a8ec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/accuracy-is-not-enough-for-classification-task-47fca7d6a8ec">Accuracy is NOT enough for Classification Task</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Language Model Concept behind Word Suggestion Feature]]></title>
            <link>https://medium.com/data-science/sentence-generation-with-n-gram-21a5eef36a1b?source=rss-81157f79faae------2</link>
            <guid isPermaLink="false">https://medium.com/p/21a5eef36a1b</guid>
            <category><![CDATA[generation]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[language-model]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Vitou Phy]]></dc:creator>
            <pubDate>Sat, 02 Nov 2019 06:17:41 GMT</pubDate>
            <atom:updated>2019-11-04T12:33:12.063Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Simple Introduction to N-Gram</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IwWFEPCzJZykRWIg" /><figcaption>Photo by <a href="https://unsplash.com/@dearseymour?utm_source=medium&amp;utm_medium=referral">Ksenia Makagonova</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>You may have seen word suggestion feature on your smartphone. As you type in one word, the keyboard understands what you are typing and suggests the next relevant word. If you select the suggested word, it will then suggest another one, and another and another until you end up having these funny sentences.</p><p>This is a simple concept, known as <a href="https://en.wikipedia.org/wiki/Language_model"><strong>language modeling</strong></a>. So what language modeling does is it reads the written text and it attempts to assign probability to the next word. Let’s look at an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*mv2ULBGFfcK09ss1rOwfVQ.gif" /><figcaption>Figure 1: Language model tries to guess what the next word is. (number on the right is probability)</figcaption></figure><p>Intuitively, suppose we have 100 words to be considered for the next word, language model takes previous word into consideration and give probability to those 100 words. Then, it can give top 3 options to the users as part of word suggestion feature. Now, let’s give a formal definition to LM.</p><h3>Language Model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AGq9IBSaXXSvG6fbKldWEg.png" /><figcaption>Figure 2: An example sentence with its notation</figcaption></figure><p>Commonly, language model is known as <strong>a way to give probability to a sentence</strong>.</p><p>But wait! Isn’t earlier we mentioned LM assign probability to the next word? Let’s break down the equation above to investigate this further.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MuxO4e24k7FPAV9jz_UZsg.gif" /><figcaption>Equation 1: Probability of a sentence based on probability of predicting next word</figcaption></figure><p>As you can see in Equation 1, LM not only can assign probability to the next word given but also can give the probability to the whole sentence. Then, the LM can understand which sentence might sound good and which might not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mSAhmHyf4c1qJPQaP2gt-Q.png" /><figcaption>Figure 3: Language model determines which sentence is more suitable than the others</figcaption></figure><p>Awesome, right? But what’s under the hood of such awesome function? There are many ways to create this language model. In this post, we will explore a simple method, called <strong>n-gram</strong>.</p><h3>N-Gram</h3><p>One key idea is ngram looks only at <strong>n words</strong> at a time. Let’s work with the example “the cat sat on the mat”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jdjzV9Ynilw1cJAwBIX2MA.gif" /><figcaption>Figure 4: Behavior of bigram</figcaption></figure><p>Suppose n=2 (also known as bigram), it will try to predict the second word based on the first one. For example:</p><ul><li><strong>the cat</strong>: Bigram tries to remember that after “the”, it should be “cat”.</li><li><strong>cat sat</strong>: after “cat”, it should be “sat”.</li><li><strong>sat on</strong>: after “sat”, it’s “on”</li></ul><p>The same thing goes with n=3. For the words “the cat sat”, trigram knows “sat” comes after “the cat”. I guess you get the idea.</p><p>This concept is scalable to n words (n-gram). So, how does ngram know all of these pattern? It’s <strong>probability theory</strong>.</p><h3>Bigram</h3><p>For simplicity, we will look the case of bigram. From the example above, we know that “cat” comes after “the”, which can be denoted as<em> P(cat | the)</em>.</p><blockquote>P(cat | the) : the probability that the next word is “cat” given the word “the”.</blockquote><p>To compute this probability, simply use this the formula below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZUpTTJjBMPSoFmH0H4vlXQ.png" /><figcaption>Equation 2: Probability for Bigram</figcaption></figure><p>where <em>c(the cat)</em> is number of occurrence of “the cat” in the entire corpus. The same goes for <em>c(the)</em>. Intuitively, this equation says that: <strong>Among all of the words “the”, how many of them are followed by “cat”?</strong> And voila, now we have <em>P(cat | the)</em>.</p><h3>Bigram vs. Trigram</h3><p>Bigram is simple and quite powerful but there are many cases it will fail to perform. For instance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZGsEWYET6GujRu55-Mp7Dw.png" /><figcaption>Figure 3: Bigram fails when it has the same previous word</figcaption></figure><p>In the beginning of the sentence, the model sees “the” followed by “cat”. If we use bigram and rely only on <strong>one previous word</strong>, it is very difficult to guess that the underline word is “mat” since it probably generates “cat” again. Fortunately, trigram or 4-gram can resolve this issue. i.e. If we see “sat on the”, it is more likely that the next word is “mat”.</p><p>However, that does not mean the longer sequence we consider, the better the prediction. For 6-gram, for instance, it might not be very common to see the exact “the cat sat on the”. Thus, it is not very efficient.</p><blockquote>Most of the time, bigram and trigram are the common choices.</blockquote><h3>Back-off and Interpolation</h3><p>There are also times where your dataset is small and 3-gram fails to recognize some exact words; thus, resulting in the probability of 0. That would make your entire 3-gram implementation not that useful anymore.</p><p>Easily you can do a simple if-else, and use 2-gram in case 3-gram fails. Or use 1-gram in the case of 2-gram fails. There is called, <strong>back-off.</strong></p><p>Another technique, <strong>interpolation</strong>, is considering different ngrams at the same time. The idea is to give weight (λ) to your n-gram so your 3-gram model can also look at the value of 2-gram and 1-gram. i.e.</p><ul><li>60% on 3-gram</li><li>35% on 2-gram</li><li>05% on 1-gram</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SImbH9dOleDpUB40x-1UGA.gif" /><figcaption>Equation 3: Interpolation of 3-gram</figcaption></figure><p>Config the weight manually until you feel it’s right. You can also use some automatic method, but we won’t go over that in this post. You can refer to <a href="https://web.stanford.edu/~jurafsky/slp3/3.pdf">this</a> for further info on how to properly set these weights.</p><h3>Implementation</h3><p>Now let’s try to use this LM to generate a sentence based on random initial word. For this task, we will use <a href="https://www.kaggle.com/gulsahdemiryurek/harry-potter-dataset">Harry Potter and the Sorcerer’s Stone Movie Script</a> to train our ngram. For the code below, you can find on <a href="https://www.kaggle.com/ruka96/sentence-generation-with-n-gram?scriptVersionId=22881807">this kernel </a>as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6304bc381724e4fefea11c80f48ee2f/href">https://medium.com/media/c6304bc381724e4fefea11c80f48ee2f/href</a></iframe><p>Then, we can count the frequency of unigram, bigram and trigram. This will be used later to compute probability.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfa3d2b25460079b424216455378f2b2/href">https://medium.com/media/cfa3d2b25460079b424216455378f2b2/href</a></iframe><p>Now that we can the count of the n-gram, we can compute its probability. We will use linear interpolation of 0.01, 0.4, and 0.5 respectively for 1-gram, 2-gram and 3-gram.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1bb1d58e502985ef77c5f02e6a09b5b/href">https://medium.com/media/c1bb1d58e502985ef77c5f02e6a09b5b/href</a></iframe><p>Let’s attempt to generate 20 words. The initial will be randomized, and choose the best next word.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a2b081291f4a1b0eda05b6c22a663ae/href">https://medium.com/media/5a2b081291f4a1b0eda05b6c22a663ae/href</a></iframe><p>So, how will this perform? Below are the results of each generation.</p><pre>Generation #1:<br>protecting the stone , but i think i &#39;ll be a wizard . . . . . . . .</pre><pre>Generation #2:<br>platform 9 3/4 ? think you &#39;re going to be the same . . . . . . . </pre><pre>Generation #3:<br>sacrifice himself , he &#39;s got a little bit . . . . . . . . . . .</pre><h3>Conclusion</h3><p>N-gram is a simple yet powerful technique to do language modeling by just looking at 2 to 3 words. It is quite practical in many applications, for instance, word suggestion on mobile device, thanks to its easy and fast in computation. N-gram, however, is not robust when it comes to generating long sentence where the current word depends on the very first word in the sentence. This long term dependency is more suitable for the model like neural network, but that is a topic for later post.</p><h3>References</h3><ol><li><a href="https://web.stanford.edu/~jurafsky/slp3/3.pdf">https://web.stanford.edu/~jurafsky/slp3/3.pdf</a></li><li><a href="https://towardsdatascience.com/introduction-to-language-models-n-gram-e323081503d9">https://towardsdatascience.com/introduction-to-language-models-n-gram-e323081503d9</a></li><li><a href="http://www.cs.umd.edu/class/fall2018/cmsc470/slides/slides_10.pdf">http://www.cs.umd.edu/class/fall2018/cmsc470/slides/slides_10.pdf</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21a5eef36a1b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/sentence-generation-with-n-gram-21a5eef36a1b">Language Model Concept behind Word Suggestion Feature</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning Concept behind Linear Regression]]></title>
            <link>https://medium.com/data-science/how-machine-learns-from-data-a-simple-method-for-co2-pollution-prediction-af18430ce12b?source=rss-81157f79faae------2</link>
            <guid isPermaLink="false">https://medium.com/p/af18430ce12b</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[predictions]]></category>
            <dc:creator><![CDATA[Vitou Phy]]></dc:creator>
            <pubDate>Sun, 20 Oct 2019 11:31:13 GMT</pubDate>
            <atom:updated>2019-11-04T12:27:27.745Z</atom:updated>
            <content:encoded><![CDATA[<h4>Applying Simple ML model on CO2 Prediction</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DArLHop2Z_wjhxzr" /><figcaption>Photo by <a href="https://unsplash.com/@alexander_tsang?utm_source=medium&amp;utm_medium=referral">Alexander Tsang</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>In the past recent years, there have been a lot of hypes on Artificial Intelligence (AI). You can find it almost anywhere from turning on the light with your voice to a fully autonomous self-driving car.</p><p>Most of modern AI requires a lot of data. <strong>The more you give, the better it learns.</strong> For instance, to train AI to understand an image of a cat, you need to give a lot of images of cats and non-cats so that it can distinguish between the two.</p><blockquote>But how exactly does AI learn from the data?</blockquote><p>In this post, we will look at a very simple model to get an idea of how AI learns. We will focus on the amount of global CO2 emission for the past 55 years and attempt to predict its amount in 2030.</p><h3>CO2 Emission Data</h3><p>The data we will be using is from <a href="https://data.worldbank.org/indicator/EN.ATM.CO2E.KT">WorldBank</a>. Unfortunately, the data is not up to the current date of 2019 (at the time of writing this). It’s from 1960 to 2014, but this will do just fine for this experiment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mx4PMGrYRu_hAeOXen1BVg.png" /><figcaption>Fig 1: Amount of CO2 Emission annually from 1960 to 2014. Source: <a href="https://data.worldbank.org/indicator/EN.ATM.CO2E.KT">WorldBank Data</a></figcaption></figure><p>On the x-axis corresponds to the year (assuming year 0 is 1960) and on the y-axis corresponds to the amount of CO2 emission. Based on the chart, we might be able to make a rough estimation of what the value of 2030 should be.</p><blockquote>Suppose we just<strong> </strong>draw a straight line that best fits this data, we could predict the future if we extend this line further and further.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kU3pGkD0jBwTN9VjbxvtDQ.png" /><figcaption>Fig 2: Fit a line and use it to make a rough estimation at year 70 (2030)</figcaption></figure><p>Keep in mind that we can not accurately predict the future. Things might change for the better, but for simplicity, we just assume that the rate of changing is constant.</p><h3>Linear Regression</h3><p>Let’s bring in a little bit of math. The blue line above might be familiar to you. It’s a simple straight line that is represented by the equation below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/161/1*w0mokU2QVDCoJvQ6v-uGUA.png" /></figure><p>Uh huh. Now you remember. Again, <strong>x</strong> is the year and <strong>y </strong>is the amount of emission. To get the line shown in Figure 2, m=446,334, and b=9,297,274. Don’t worry about m and b. I will explain them in detail later.</p><p>In case we want to know info on the year 2030 (year 70 if we count from 1960), we can now use our equation above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*h52SqelmQoclyHrliJAPOw.png" /></figure><p>Now as promised, let’s take a close look at what <strong>m</strong> and <strong>b</strong> are.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N2xt8cMLIhWiIFNYmkzqpg.gif" /><figcaption>Fig 3: Behavior of m on the line</figcaption></figure><p>In Figure 3, as we change the value of m, the line rotates around. Hence, variable m controls<strong> the direction of the line</strong>. Whereas in Figure 4, the variable b controls <strong>the position of the line</strong> by moving it up or down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J-iWWnKUxEcNbm-x0yejhQ.gif" /><figcaption>Fig 4: Behavior of b on the line</figcaption></figure><h3>Learning Process</h3><blockquote>With m and b, we can control the line and adjust it to best fit our data.</blockquote><p>The question now is how do we find the value of variables m and b? The idea is the following:</p><ol><li>Randomize the value of m and b.</li><li>Give the variables to a loss function to determine how bad the line is compared to the data, also known as error rate.</li><li>Adjust the value of m and b based on the error rate.</li><li>Go back to Step 2. Repeat until the variables stop changing.</li></ol><h3>Loss Function</h3><p>If our line is very bad, this loss function will give a very big error. At the same time, if the line fits the data well, the error will be small.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wdp8HIGXxrI-JEgBdeyDXA.png" /><figcaption>Fig 5: The difference between predicted line and actual data</figcaption></figure><p>The line has its predicted value <strong>y’</strong> every year. Then, we can compare the predicted value <strong>y’</strong> to actual value <strong>y</strong> to find the difference. We compute this value on every year and take its average. This is also known as <em>Mean Squared Error</em> (MSE).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*9x_UfZ6XKvJarktQx-t1dQ.png" /><figcaption>Fig 6: Closed form of MSE</figcaption></figure><p>Now we are almost ready to update our variables. There is one small catch. The error rate we found earlier is always positive. Pretty much we do not know which direction should update our line. Should it rotate clockwise or counter-clockwise? That is when <strong>Gradient Descent </strong>comes in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gMiy_eU-H5AJc8py4USjyA.png" /><figcaption>Fig 7: Formula to update each variable (in this case, variable <em>m</em>)</figcaption></figure><p>In a nutshell, this tells the direction and how much each variable affects the error. <strong>The more effect it has, the more value it should change.</strong> Then, we can use this information to update our variables. We won’t dive deep down into the derivative, but if you are interested, you can check out <a href="https://www.coursera.org/learn/machine-learning/lecture/kCvQc/gradient-descent-for-linear-regression">this video</a> on Coursera. I find the explanation there quite clear.</p><p>Note the alpha <strong>α</strong>, also known as, <strong>learning rate</strong>, is to control how much we should update our variables. Usually, we set it to a small value, like 0.001, so that we can slowly update our variables toward optimal value.</p><blockquote>Good news: in practice, we don’t manually do this derivation.</blockquote><p>Popular frameworks like Tensorflow or PyTorch will compute this automatically. But I put it here to give a brief idea of how it can know which direction to change the value.</p><h3>Implementation</h3><p>So, do you need to code everything as described above to get linear regression working? Fortunately, many existing libraries simplify everything for you. In this example, we will explore <a href="https://scikit-learn.org/">scikit-learn</a>, a machine learning library built for Python, to predict CO2 emission.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3f9f045f6491f9b2e176b2fc32f7b9d/href">https://medium.com/media/e3f9f045f6491f9b2e176b2fc32f7b9d/href</a></iframe><p>With just a few lines of codes, scikit-learn makes linear regression very accessible. Line 9 alone does all the necessary steps needed to train the model. Phew, you were worry for nothing, weren’t you? Not only for linear regression, but also this applies to implementing many other ML algorithms with just a few lines of codes.</p><h3>Conclusion</h3><p>That’s it. Not so complicated right (except the derivation part)? Linear regression is a simple method yet quite effective even though it is just a straight line. In this post, we only looked at the case where there is only one variable (year). Actually, this can be extended to handle multiple variables, but that is the topic for later post.</p><h3>References</h3><ol><li><a href="https://en.wikipedia.org/wiki/Linear_regression">https://en.wikipedia.org/wiki/Linear_regression</a></li><li><a href="https://towardsdatascience.com/introduction-to-machine-learning-algorithms-linear-regression-14c4e325882a">https://towardsdatascience.com/introduction-to-machine-learning-algorithms-linear-regression-14c4e325882a</a></li><li><a href="https://developers.google.com/machine-learning/crash-course/descending-into-ml/linear-regression">https://developers.google.com/machine-learning/crash-course/descending-into-ml/linear-regression</a></li><li><a href="https://www.coursera.org/learn/machine-learning/lecture/kCvQc/gradient-descent-for-linear-regression">https://www.coursera.org/learn/machine-learning/lecture/kCvQc/gradient-descent-for-linear-regression</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af18430ce12b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-machine-learns-from-data-a-simple-method-for-co2-pollution-prediction-af18430ce12b">Machine Learning Concept behind Linear Regression</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reinforcement Learning Concept on Cart-Pole with DQN]]></title>
            <link>https://medium.com/data-science/reinforcement-learning-concept-on-cart-pole-with-dqn-799105ca670?source=rss-81157f79faae------2</link>
            <guid isPermaLink="false">https://medium.com/p/799105ca670</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[dqn]]></category>
            <dc:creator><![CDATA[Vitou Phy]]></dc:creator>
            <pubDate>Sun, 06 Oct 2019 13:45:38 GMT</pubDate>
            <atom:updated>2019-11-04T12:35:21.187Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Simple Introduction to Deep Q-Network</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F5Q14EjnOJZc&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D5Q14EjnOJZc&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2F5Q14EjnOJZc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/688d7de1d1f78dd3eee31a2a43055cc4/href">https://medium.com/media/688d7de1d1f78dd3eee31a2a43055cc4/href</a></iframe><p>CartPole, also known as <a href="https://en.wikipedia.org/wiki/Inverted_pendulum">inverted pendulum</a>, is a game in which you try to balance the pole as long as possible. It is assumed that at the tip of the pole, there is an object which makes it unstable and very likely to fall over. The goal of this task is to move the cart left and right so that the pole can stand (within a certain angle) as long as possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cD9dV30P5D-9z-_s0AA2eQ.png" /><figcaption>Figure 1: We can move the cart ONLY to the left and right.</figcaption></figure><p>In this post, we will look at reinforcement learning, a field in artificial intelligence where the AI explores the environment all by itself by playing the game many many times until it learns the right way to play the game.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FE7TfYJ2eEctsMt-YGsyNg.gif" /><figcaption>(Figure 2)<strong> Left</strong>: start of the training. <strong>Center:</strong> After a few episode of training. <strong>Right:</strong> Agent fully trained</figcaption></figure><p>As you can see here, at the beginning of the training, the agent has no idea of where to move a cart. After a while, the agent moves toward a direction but, of course, it is impossible to bring the pole to the other side with such speed. For the last one, the agent knows the correct way to balance the pole which is the move left and right repeatedly.</p><h4>Rewards</h4><p>Let’s try to understand this game a little bit more. Again, the objective is to stay alive as long as possible. The longer you keep the pole standing, the more score you will get. This score, also called <strong>reward</strong>, is what we give to the agent to know if its action is good or not. Based on that, the agent will try to optimize and pick the right action. Note that, the game is over when the pole exceeds 12-degree angle or the cart is going out of the screen.</p><p>But how does the agent know the current status of the pole? What should the data look like?</p><h4>States</h4><p>The current condition of the cart-pole (of whether it tips over to the left or right) is known as <strong>state</strong>. A state can be the current frame (in pixels) or it can be some other information that can represent the cart-pole, for instance, the velocity and position of the cart, the angle of the pole and pole velocity at the tip. For this post, let’s assume the state of the cart is the 4 properties mentioned above.</p><p>Depending on the action we take, it can lead to different other states. Suppose the pole is starting straight, if we go left, the pole is mostly to go right, which is a new state. Therefore, during each time-step, any action we make will always lead to a different state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HNcp0AcTME4WRKqfoDc_dw.png" /><figcaption>Figure 3: When we move the cart to the left, the pole tends to fall to the right side, and vice versa for the other direction.</figcaption></figure><h4>Q-Learning</h4><p>From the state diagram above, we can see that if we make the right decision, the pole will not fall over and we will get a reward. In other words, for those <strong>state and action pairs</strong> that lead to further and further states is also <strong>expected</strong> to get a large reward. So, let’s call this expected reward for each state-action pair as Q-value denoted as <em>Q(s,a)</em>.</p><p>During a state <em>(s)</em> and the agent takes an action <em>(a)</em>, they will immediately get the reward for making that action (1 if the game is still on and 0 otherwise). However, earlier we mentioned that we want to consider the <strong>potential future reward of that state-action pair</strong>. Let’s consider this case formally with the equation below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*fRIL3u5U6KeBRicgRmttNw.png" /><figcaption>Equation 1 : Idea behind Q-Learning</figcaption></figure><p>Intuitively, we want to know <em>Q(s,a)</em> which is the expected reward we can get if we are in the state <em>(s)</em> and making <em>(a)</em> action. After getting a reward <em>(r)</em> by making an action <em>(a)</em>, we will reach another state <em>(s’)</em>. Then, we just look up in our Q table and find the best action to take at state <em>(s’)</em>. So, the idea here is we don’t need to consider the entire future actions, but only the one at the next time-step. The gamma symbol <em>(γ)</em> indicates how much we should focus on the future reward of state s’.</p><p>At the beginning of the training, we don’t know the Q-value for any state-action pair. Based on the equation above, we can make some changes to Q-value little by little toward a direction of optimal value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*CHD37XHxPlGFweR4Ou3w6A.png" /><figcaption>Equation 2 : Updating Q(s,a)</figcaption></figure><p>The equation might look a bit terrifying. Don’t worry. We’ll gonna break it down to see what’s going on here with the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4BmxIBuHSalvK2HeX7pQAQ.png" /><figcaption>Figure 4: Breaking down equation 2</figcaption></figure><p>Here, the <em>Q(s,a)</em> will be updated based on the difference between what we think we know about <em>Q(s,a)</em> and what the current episode tell us about <em>Q(s,a) </em>(what it should be). If our <em>Q(s,a)</em> is overestimated, the value in the red dashed box will be negative and we will lower <em>Q(s,a)</em> value by a little. Otherwise, we will increase <em>Q(s,a)</em> value. The amount we make changes to <em>Q(s,a)</em> depends on the difference (red box) and the learning rate (α).</p><p>There is one problem with current Q-Learning. That is the state space is huge. Each small change to the angle of the pole or the velocity of the cart represents a new state. We would need to have a very big memory to store all possible states. For this cart-pole, it may be possible to handle that many states but for more complex games like StarCraft 2 or Dota 2, Q-Learning by itself is not enough to get the job done.</p><h4>Deep Q-Learning</h4><p>To cope with this problem, we need something to approximate a function that takes in a state-action pair <em>(s,a)</em> and returns the expected reward for that pair. That is when deep learning comes in. It is renowned for approximating a function just from the training data. Keep in mind that we will not go through the detail of the neural network in this post. It will be just a brief on how we can incorporate deep learning with reinforcement learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e4zJseD0jnbEpiL-Vs2BHw.png" /><figcaption>Figure 5: Incorporating network network in Q-Learning</figcaption></figure><p>Suppose we want to know <em>Q(s, a=right)</em>, we feed in the state <em>(s)</em> of the environment into the model. Let the neural network do the calculation, and it will return 2 values. One is the expected reward when making the left move and another is for making the right move. Since we are interested in <em>a=right</em>, we would just get the value from the lower node of that output. Now we have <em>Q(s,a)</em> by using the network.</p><p>To fully train the network, loss function is essential. Intuitively, before the network output an approximated value <em>Q(s,a)</em>, we already have an idea of what the value should be (based on equation 2). Hence, we can punish the network for the mistake it makes, and let it learn that mistake through back-propagation.</p><h4>Putting It Together</h4><p>Now we have talked about the state, reward, action, Q-learning and DQN specifically on this cart-pole environment. Let’s look at the result of DQN on the cart-pole environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LbzK0vhtoIzrBjb8mK8KHw.gif" /><figcaption>Figure 6: Playing cart-pole with DQN after fully trained</figcaption></figure><h4>Conclusion</h4><p>So, this is it. We just went through the concept of DQN on a cart-pole game. DQN was successfully applied to many more games especially Atari games. It’s pretty generic and robust. So, next time you have an environment in mind, you can just plug-in DQN and let it learn to play the game by itself. Keep in mind that recently, there are many other deep-reinforcement learning techniques that can learn more complex game like Go or Dota 2 better and faster, but that is the topic for another time.</p><h4>References</h4><ol><li><a href="https://arxiv.org/pdf/1312.5602.pdf">https://arxiv.org/pdf/1312.5602.pdf</a></li><li><a href="https://www.analyticsvidhya.com/blog/2019/04/introduction-deep-q-learning-python/">https://www.analyticsvidhya.com/blog/2019/04/introduction-deep-q-learning-python/</a></li><li><a href="https://web.stanford.edu/class/psych209/Readings/SuttonBartoIPRLBook2ndEd.pdf">https://web.stanford.edu/class/psych209/Readings/SuttonBartoIPRLBook2ndEd.pdf</a></li><li><a href="https://gym.openai.com/envs/CartPole-v1/">https://gym.openai.com/envs/CartPole-v1/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=799105ca670" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/reinforcement-learning-concept-on-cart-pole-with-dqn-799105ca670">Reinforcement Learning Concept on Cart-Pole with DQN</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>