<?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 Utkarsh Malaiya on Medium]]></title>
        <description><![CDATA[Stories by Utkarsh Malaiya on Medium]]></description>
        <link>https://medium.com/@utkrshm?source=rss-666b41184940------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UCU779TBFGb22nxQQaYMzQ.jpeg</url>
            <title>Stories by Utkarsh Malaiya on Medium</title>
            <link>https://medium.com/@utkrshm?source=rss-666b41184940------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 09:09:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@utkrshm/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[My learnings from Building Deep Learning Models from Scratch]]></title>
            <link>https://ai.plainenglish.io/my-learnings-from-building-deep-learning-models-from-scratch-47c920acaf03?source=rss-666b41184940------2</link>
            <guid isPermaLink="false">https://medium.com/p/47c920acaf03</guid>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[advice]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Utkarsh Malaiya]]></dc:creator>
            <pubDate>Mon, 16 Oct 2023 10:03:14 GMT</pubDate>
            <atom:updated>2023-10-25T15:34:25.912Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building deep learning architectures from scratch isn’t just a cool project you build to brush up your resume, it is also a great way to test and extend your understanding of the underlying details of these architectures, improve your math and coding skills and this proves to be a very good tool to have when you’re going to be building more complex versions of these models. As it also turns out, this tests your debugging skills a lot more than you’d imagine.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ivcCK2TN0HaiU6yy" /><figcaption>Photo by <a href="https://unsplash.com/@steve_j?utm_source=medium&amp;utm_medium=referral">Steve Johnson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This past week, I set out to build a simple Feedforward Neural Network and a Convolutional Neural Network from scratch, without using GPUs and tensors, i.e., only in NumPy, and I’d finished the <a href="https://course.fast.ai/">FastAI Course Part 1</a> only 3 days before I decided on this, so suffice it to say, I didn’t have a vast amount of experience before I started this.</p><p>My goal behind this was to test my knowledge from that course and to test my programming and math skills. I’ll admit, at the time, I didn’t think this would be much difficult.</p><p>The result: I succeeded! I built a slow Feedforward Neural Network to work on the Titanic dataset (<a href="https://www.kaggle.com/code/utkmal/ann-in-numpy-on-titanic-dataset-0-765">view here</a>), which I’d say worked pretty well, and then built a base CNN on the MNIST dataset (<a href="https://github.com/utkrshm/CNN-in-NumPy">view here</a>) that also did averagely well. I got an accuracy on both models of around 70% on the test set after extensive training, so I can’t exactly call them good. More than the performance of the models, this was a phenomenal learning experience as I learnt a whole lot of things that both, FastAI part 1 and 3 courses of Deep Learning Specialization did not, about building deep learning models (They’re both great courses, believe me but these were things you can’t learn in a course/class). In the following portion of the article, I’ll tell you all those things, so if you’re thinking of building deep learning models from scratch, you won’t have to struggle with them.</p><p><strong>tl;dr:</strong></p><ol><li>Optimize for a good learning experience, not a fast and accurate model.</li><li>You can un-generalize the model if you want.</li><li><a href="#bcc8">If you can’t code it yourself, you probably don’t understand it well enough.</a></li><li>The math and the code are only 50% of the entire process, debugging is the rest.</li><li>If you’re stuck somewhere, start by working out the matrix shapes with a pen and paper.</li><li>Always double-check the variables. ALWAYS.</li><li>Test everything out as you code it, not all at once.</li><li>Don’t be afraid to ask for help. Just, give it your best before you do.</li></ol><p><strong>1. Optimize for a good learning experience, not a fast and accurate model</strong></p><p>Chances are, if you’re reading till here, you’re thinking of building deep learning models from scratch, or you’ve built one already. If the former, I would very much encourage you to not prioritize building a State-of-the-art model or something similar but rather to prioritize what you’re learning.</p><p>If you want to build a SOTA model, you can very easily use TensorFlow or PyTorch, and train a very large, deep Neural Network for 8–9 hours on a GPU can get a SOTA model. But when you’re trying to build these from scratch, chances are they are going to be very scrappy models, that can just barely get good accuracy after training for 1000’s of epochs.</p><p>This is, of course, assuming that you’re only using NumPy like I did, but still, you don’t want to spend a lot of computing power for a from-scratch model that you or anyone else may not use later on.</p><p><strong>2. You can un-generalize the model if you want</strong></p><p>Although I don’t recommend doing this, this isn’t a crime either.<br>If, like me, you’re building an MNIST-classifying CNN, then the MaxPooling layer you code or the Convolutional layer you code doesn’t have to generalize to images that have 3 colour channels. I admit, I didn’t create my Convolutional layer to use an RGB image, no, I just used it such that it would work for an image in the MNIST dataset because I was trying to make the model fit just for the MNIST dataset, I don’t plan on using it later.</p><p>If you want to build a general model, please do so. I encourage you to. Since you’re building these models to learn the nitty-gritty details of these models, you might as well go all the way. I didn’t, because even though I wanted to, it added a layer of complexity that I wasn’t prepared for, and I do plan on generalizing my model to 3 channel images, but for now, I decided not to do so. This isn’t to say you should always do this. You can do this in these kinds of models because they’re your personal projects, but not with models you’re building for your company or ones you plan on productionising.</p><p>However, for this project, even if you don’t build generalizable models, that’s okay. This is a learning opportunity, even if you learn 90% from this opportunity, that’s not a wasted opportunity. Maybe you’ll come back to it later.</p><p><strong>3. If you can’t code it yourself, you probably don’t understand it well enough.</strong></p><p>It’s very easy to go to a GitHub repository or an article someone wrote about something and copy that code without understanding what it’s doing, but you don’t want to do that in this scenario.<br>If you’re building from scratch models to understand what’s going on under the hood, that’s probably the worst thing you can do.</p><p>So if there’s a concept that you can’t code by yourself, there’s something in there to suggest that you don’t understand that concept well enough yourself. And you’re only admitting that to yourself, so there’s no shame in saying that. It took me over 3 days to code the Convolutional layer in my model, because that’s how long it took for me to understand that layer. It’s fine.</p><p>My suggestion is to use <a href="https://fs.blog/feynman-technique/">Feynman’s technique</a> and write on a paper about the concept you don’t understand as if you were explaining it to a child. I did that with the Convolutional layer (<a href="https://imgur.com/wYUEGfh">see my explanation here</a> and <a href="https://imgur.com/6ccbZkr">my supporting diagram here</a>) and not only did it increase my understanding of the layer, but it also helped me find the gaps in my knowledge so I could very specifically improve those areas.</p><p>If you succeed in explaining the concept successfully, then your knowledge is thorough, and if you can’t, then you can watch videos about the things you’re unclear on, and improve your understanding.<br>This will allow you to easily code everything from scratch while maximizing your understanding of the concepts.</p><p><strong>4. The math and the code are only 50% of the entire process, debugging is the rest</strong></p><p>This is true for all of Machine Learning, so the faster you internalize this, the better.</p><p>When you are building these models, it’s easy enough to learn the math and write the code from pseudocode, but the real challenge I encountered was to debug my code. This is one of the reasons why I thought of building a Feedforward Neural Network despite having done it in the Deeplearning.ai specialization. In the assignments there, you don’t get the chance to debug your code because mostly, what you have to do is translate pseudocode in those assignments.</p><p>Debugging your code is an important skill as a programmer, but it becomes even more important as a Machine Learning developer. That is because in ML/AI, you don’t just have to debug the errors, you also have to make sure the dimensions match, the gradients are being updated properly, the loss is going down and the accuracy goes up. Most of this happens under the hood, so it becomes much more difficult to debug these things.</p><p>The biggest headache I had when building both my models was to make sure my loss went down, because it was either stagnant or it was increasing. Same with accuracy. If it’s increasing, that’s easy to debug. You’re putting a negative sign somewhere it’s not supposed to be, or you’re putting it where it is supposed to be. When it is stagnant, that’s a whole different headache.</p><p>For this reason alone, I can say that I spent half the time debugging my model, and only half the time actually writing the code for the layers and the pipeline.</p><p>My tip to make debugging easier is to print out everything, starting from the gradients to the loss to the weights of different layers to make sure they’re decreasing. Sometimes, it’s also a matter of your model’s complexity or the amount of data you are training your model with also causes bugs so be sure to check for that too.</p><p>The next two points also deal with specific examples that’ll help you catch bugs easily, ones I had to learn the harsh way.</p><p><strong>5. If you’re stuck somewhere, start by working out the matrix shapes with a pen and paper</strong></p><p>The only math you need in Deep Learning, as per what I’ve encountered, is Matrix Multiplication and the knowledge of derivatives.</p><p>If you know how to calculate derivatives, you’re golden. If you use a framework like TensorFlow or PyTorch, you don’t even need to calculate the gradients because the framework does that for you.<br>Even when you’re building deep learning models from scratch, you only need basic knowledge of derivatives for backpropagation, and you’re good.</p><p>Matrix multiplication, however, is the foundation that a deep learning model lives on. Your entire processes are carried out in n-dimensional matrices, everything. So whenever you face any problem, your loss is stagnant, or the accuracy is coming out to be NaN or anything else, I suggest first working out your matrices’ shapes across all your layers with a pen and paper. You can also use NumPy to tell you all the matrices’ shapes, but I find working them out on paper to much easier for me.</p><p>I cannot tell you how many times over the last week I faced an error that I wracked my head over for hours, all because the matrix dimensions didn’t match, and it was leading to some inconsistency in my model and felt embarrassed afterwards, because it was a silly mistake.<br>I found that, in my case, the only mistake you can make, relating to the math is to not check the matrix shapes’ consistency across layers. Don’t be like me, don’t wait 2–3 hours to work your matrix shapes.</p><p>In things like this, it’s better to be proactive. So I suggest, if you’re thinking of building these models, work out your matrix shapes as you decide on the input and output of each layer. Saves you a lot of hassle in the building phase. And one more thing,</p><blockquote>Remember, <strong>assert </strong>(in Python) and <strong>.shape</strong> are your best friends to deal with these problems.</blockquote><p><strong>6. Always double-check the variables. ALWAYS.</strong></p><p>I made this mistake one too many times, more than I care to admit, but it’s possible to do that. When there are many lines of code on your 15.6-inch screen, and your variables are so descriptive and similar as mine were, it’s a possibility for this to happen.</p><p>I would’ve spent 3–6 fewer hours on both projects if I’d just double-checked if I was using the correct variables everywhere. I don’t think this is a mistake many of you will make, but I did, and it was very dumb of me to make this mistake (But I’m learning, so I don’t plan on staying this dumb).</p><p>To avoid this, don’t make the mistake of keeping your variables descriptive. Have a key whenever necessary for your variables, but keep the variables distinctive and short. Reduces the chances of you making the same mistakes I did.</p><p><strong>7. Test everything out as you code it, not all at once.</strong></p><p>This is a general tip for whenever you’re doing any kind of programming, but I had to learn the hard way just how important this is when you’re building out Neural Networks from scratch.</p><p>When you’re building these kinds of projects, you don’t have anything laid out in front of you. You don’t know what the outputs will look like, or the backpropagated weights will look like, or even the gradients. This makes the entire process daunting.</p><p>As soon as you start to code, you need to have a clear plan of how you’re going to be testing different parts of your models, how you’ll test the forward propagation for each layer, how you’ll test the backpropagation or the gradient updation functions of your model. And if you don’t test them as soon as they’re ready, if you don’t have a unit test ready for them, they will cause a whole heap of problems when you’re testing out the entire pipeline/model.</p><p>This is something I didn’t do (because I was an idiot not to do this), but I highly recommend you do it, but <em>always</em> have a parallel script that uses TensorFlow or PyTorch to test your functions/layers’ working. <br>If you’re building a Fully Connected (or Dense) layer and you’ve just written the forward propagation code for it, have a script that has a set seed for both, NumPy and the framework, with both of them having the same settings, and compare the results of both the models. They may not be identical, but you’ll know if your implementation is working correctly or not.</p><p><strong>8. Don’t be afraid to ask for help. Just, give it your best before you do.</strong></p><p>Again, a pretty general tip but it should be known.</p><p>I didn’t build these models all on my own. I was stuck many times when building these out, and I did ask for help on public forums, and private communities because there were times I couldn’t do it on my own no matter how much I tried. Sometimes, an external eye can spot errors in your code much more easily than you.<br>(Remember how I mentioned earlier that I would’ve spent 3–6 hours less on the project if I’d double-checked that I was using the right variables, well I didn’t catch that mistake by myself, someone told me on an online forum about this mistake because I was unable to find it even after a long time.)</p><p>When I didn’t understand the math, I watched YouTube videos and watched tutorials to see how to do something if I couldn’t do it myself first. That’s all to say, you should know when you’re lacking in some help and ask for others’ help rather than try and beat yourself up over not being do something.</p><p>However, all I ask if you’re planning to embark on this journey, or are already on it, is to first try everything yourself. You want to learn from this experience as much as you can, so make sure you’ve exhausted all your possibilities and your knowledge before you ask for help.</p><p>That’s it, those are the main things I learnt when building a CNN and an ANN (Feedforward network) from scratch, in NumPy without using pre-defined frameworks. <br>To be honest, this experience was well worth all the headaches it caused me because the result made it all worth it. I have learnt a lot from this experience, and I highly recommend, if you’re in the ML field and haven’t done this (highly doubt there’s going to be anyone who hasn’t), give it a try. Worst thing that’ll happen is that you’ll realize you don’t understand everything about these things.</p><p>Thanks for reading this!</p><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us on </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><strong><em>(X</em></strong>), <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, and <a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47c920acaf03" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/my-learnings-from-building-deep-learning-models-from-scratch-47c920acaf03">My learnings from Building Deep Learning Models from Scratch</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using reinforcement to make machines human-like]]></title>
            <link>https://utkrshm.medium.com/using-reinforcement-to-make-machines-human-like-9a4a21a3da0e?source=rss-666b41184940------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a4a21a3da0e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai-x-psychology]]></category>
            <dc:creator><![CDATA[Utkarsh Malaiya]]></dc:creator>
            <pubDate>Sun, 13 Feb 2022 19:08:39 GMT</pubDate>
            <atom:updated>2022-02-13T19:08:39.659Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using reinforcement to make machines, human-like</h3><h4>An introduction to Reinforcement Learning, the ML paradigm enabling autonomous vehicles to drive, machines to play games like Chess, Go like [and better than] humans do, through reinforcement.</h4><p>When you’re talking about the nature of learning, the first thing that may pop up in your mind may be learning through interaction.<br>That seems fair, that’s how we learn too.</p><p>The trial and error model — which happens to be at the core of learning through interaction — is a very effective way by which we learn to go from zero to hero in anything, be it walking, conversing with others, anything. You experiment first, see how people/things in your surroundings respond to your action and then you decide on your next action.<br>If the response is pleasant, you are more likely to repeat your previous action; if not, you’re likely to take some other action.</p><p>When learning fundamental things like walking or talking, you don’t have an explicit teacher. You just observe your surroundings and take action accordingly.<br>A baby first tries to stand via support, then without support, walk via support, and finally without support. However, the actions it takes are not entirely on its own, it receives a “response” from either laws of Physics or humans around it in the form of cuddles (pleasure) or falling down (pain). Depending on the response, the baby then evaluates if it should repeat the action (if it got cuddles), or change it a little bit (when it fell down).</p><p>That <em>feedback</em> it receives, that pleasure or pain, is central to this cycle of learning. This feedback allows the learner (the baby in this case) to evaluate how good each of its actions was, and, naturally, plays a part in deciding the future actions.<br>Generally, this <em>feedback</em> is received in the form of a reward or a punishment, which either encourages its behavior or disapproves it.<br>This phenomenon, which uses negative or positive feedback to ultimately shape the behavior of the agent, was described by B.F. Skinner as the <strong>principle of reinforcement</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/0*HMAtyTMgSrpazzyt.jpg" /><figcaption>This theory, wherein the baby repeats/changes the action depending on the feedback signal from its surroundings, is called <strong>the principle of reinforcement</strong>, which was proposed by BF Skinner.</figcaption></figure><p>Reward-based reinforcement (reinforcement that uses explicit reward as the feedback signal) is at the very core of why humans do anything; from learning to play a game (where the reward is the player’s position on the leaderboard of that game), to scoring good marks in exams (where the reward is the “gift” you and your parents had already decided, that was supposed to be given to you when you score high), to working hard at one’s job (where the reward is financial incentives and retirement benefits).</p><p>However, in recent years, this theory of reinforcement, this trial-and-error model of learning, has been adopted to make intelligent artificial systems that have a certain “human-ness” about them, that no machines have ever had.</p><p>This can be observed in AI systems that can play human games (AlphaZero, AlphaGo, and IBM Watson), crack jokes, debate with humans (<a href="https://www.theverge.com/2018/6/18/17477686/ibm-project-debater-ai">IBM’s Project Debater</a>), and drive better than them (self-driving cars).</p><p>But then, a question arises:</p><p><strong>How is the principle of reinforcement added to machines to achieve this so-called “human-ness”?</strong></p><p>Tweak a little bit details about Skinner’s principle to make it “machine-friendly”, and there’s your answer; all of these systems are powered by a subset of Machine Learning called <strong><em>Reinforcement Learning (RL)</em></strong>, something that has been creating a huge buzz recently and, according to me, will be the key to making Terminator-like human robots (general AI).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/0*N8nqQ4ZNJ76d-13w.gif" /><figcaption>Reinforcement Learning will be key to creating making Terminator-like robots that’ll take over humanity! 😈</figcaption></figure><p>(Don’t worry, I’m just kidding…<br>They won’t take over<br>Well, not at least for the next 40–50 years)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*az2sfXpel3bKtNOQMWcnDw.png" /><figcaption>Reinforcement Learning in Machines has been derived from Skinner’s Theory of Reinforcement for humans and animals</figcaption></figure><h3>What is Reinforcement Learning?</h3><p><strong>Reinforcement Learning</strong> is a <strong>subset of Machine Learning</strong>, based on the principle of reinforcement, where</p><blockquote><em>An </em><strong>agent</strong><em> interacts with an </em><strong>environment</strong> <em>through experimentation (trial and error) by taking </em><strong>actions<em> </em></strong><em>by implementing a feedback loop to maximize its </em><strong>cumulative reward</strong><em>.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/0*DXjfsY-biQpJFhaP" /><figcaption>Right, sorry!</figcaption></figure><p>Let’s simplify that definition with an analogy about how a child may learn not to play with fire.</p><blockquote>In a freezing winter, your child is left alone in a room with a fireplace for the first time, and is wandering around the room.<br>As it comes near the fire, it starts to feel warm and happy, so it starts to get closer to the fire because it wants to feel more happy and warm, and eventually, it starts to very warm and very happy.<br>But as it tries to touch the fire, it gets hurt and moves away from the fire.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*rmEhGKTngyBRA_QYBioymQ.gif" /><figcaption>[Thanks to <a href="https://www.linkedin.com/in/s-p-shovon-5b1244207/">SP</a> for this GIF] If the child now comes near a fire after this, it will share Frank’s sentiments</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*Neyb3ScSzdJ-gt_kUPb-pA.png" /></figure><p>The baby is very similar to something in Reinforcement Learning called an <em>agent</em>. It is left in an unknown room and not told what to do or what not to do, so it explores the room. The room, in terms of Reinforcement Learning, is called the <em>environment</em>.<br>Soon, the child finds that at a particular location in that room, he feels warm and happy, and through interaction with the environment, he finds that he feels warmer and happier the closer it is to the fire. The location of the child in the room is called the <em>state</em> of the child, and the feeling of warmth and happiness is called the <em>reward</em>.</p><p>An RL agent, like the child, is put in an environment without any instruction, and starts interacting with the environment by exploring the states in the environment through trial-and-error, and is motivated by reward while doing the same, and it tries to keep most of it when the task ends.</p><h3>Key Terms in Reinforcement Learning:</h3><p>Formally defining all the terms I used in the previous section:</p><ul><li><strong>An agent</strong> is a decision-maker or the action-taker;</li><li><strong>The environment</strong> is everything surrounding the agent;</li><li><strong>The state</strong> of the agent is the <em>situation</em> that our agent finds itself in, in the environment, as viewed by the agent itself.</li><li><strong>An action</strong> is a movement/activity that an agent makes in the environment to change its state.</li><li><strong>The Reward</strong> is a numerical value of how well our agent has done in his quest.<br>This is the number the agent tries to maximize, which is most often the goal of our agent.</li></ul><h3>The Process</h3><p>A general RL problem, where an agent works within the environment to maximize its reward/return with each changing state, can be illustrated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/0*IUIQec06_vNuSJ1g" /><figcaption><strong>where t ∈ [0, ∞]</strong></figcaption></figure><p>The interaction between the agent and the environment takes place in the form of a loop (see illustration above):</p><p>When starting an iteration, the agent receives a state <strong>s₀ </strong>(s-sub-0) from the environment. Depending on the state s₀, the agent takes an action <strong>a₀</strong> (a-sub-0)to transition to a new state <strong>s₁ </strong>and receive a reward <strong>r₁</strong>, which are both given by the environment based on the action.<br>The number in the subscript denotes the <em>time step </em>of the iteration, i.e., how many loops have been completed. In any time step <strong>t</strong>, there are four values involved: <strong>sₜ, aₜ, sₜ₊₁, rₜ₊₁</strong></p><blockquote>Based on the number of time steps, there are two types of tasks in Reinforcement Learning:</blockquote><blockquote><strong>Episodic tasks</strong>: These tasks have finite time steps, have a terminal state (end state), and can end.<br><strong>Continuous tasks</strong>: These are tasks that have infinite time steps, no terminal state and never end.</blockquote><p>This process continues until the task is completed or the agent has maximized its reward.</p><h3>Markov Decision Processes:</h3><p>For almost all AI topics, there are mathematical frameworks to address and simplify the problems.<br>For Reinforcement Learning, that mathematical framework is called <strong>Markov Decision Processes (MDPs)</strong>, where an MDP is used to give insight into the environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*9cEBv2oXvT5BbYjPyeZrXA.png" /><figcaption>General RL problem as an MDP</figcaption></figure><p>MDPs are model decision processes where all the states follow the <strong>Markov property</strong>, which says that</p><blockquote>The future is independent of the past given the present</blockquote><p>I.E., the action that our agent takes is dependent only on its current state, and all the states before our current state can be discarded as we have no use for it.<br><em>The </em><strong><em>Markov property can be observed during a game of chess</em></strong><em> ♟️, where the move a player makes is dependent only on the current board settings, and </em><strong><em>not</em></strong><em> on the entire history of the board, or every move played since the start.<br>Mathematically, the Markov property can be defined as:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/0*rNwZ9x-O0jC78OkN.png" /><figcaption>Mathematical expression for the Markov Property</figcaption></figure><p>An MDP has five key elements that it uses to describe the environment: <br><strong>⟨S, A, </strong>ℙ<strong>, R, γ⟩</strong>, where</p><ul><li><strong>S</strong> is a set of all the possible states, also called the <em>state space</em></li><li><strong>A</strong> is a set of all the actions, also known as the <em>action space</em></li><li>ℙ<strong> </strong>is the state transition probability, i.e., the probability of going from current state <em>s</em><strong><em>ₜ</em></strong><em> </em>(or s)to another successor state <em>s</em><strong><em>ₜ₊</em></strong><em>₁ </em>(more generally denoted with s’), which is given by the state probability transition matrix.<br>This function is mostly denoted by <strong>Pₐ(s,s’)</strong>. This notation means, “what is the probability of the going from current state to successor state, depending on the action taken”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*cHUnf-LZ43BfU55IvgbdAQ.png" /><figcaption>This is the probability transition matrix, where each row represents the probability of going from our current state to each successor state</figcaption></figure><ul><li><strong>R</strong> is the reward function.<br>The reward function is denoted by <strong>R(s, a, s’)</strong>.</li><li><strong>γ </strong>is the Discount Rate / Discount Factor<br>Discount Rate, usually an integer between 0 and 1 (optimally, the value should be between 0.2 and 0.8), is how much our agent values future rewards (rewards it gets in the future) versus immediate rewards.<br>If we are to get a reward <em>r,</em> <em>n </em>steps in the future, then the worth of that reward to our agent, in its current state, is given by (<strong>γⁿ)*r</strong>.<br>So if we were to get a reward r=100, n=5 steps in the future, and our discount rate γ=0.8, then the worth of the reward to our agent in its state will be: (0.8)⁵ * 100 = <strong>32.768 </strong>(Don’t worry, as our agent comes closer to this reward, its value will increase)</li></ul><h4>Rewards and Returns</h4><p>Reward mechanisms are the backbone of Reinforcement Learning.</p><p>A reward, as defined earlier, is the numerical value of how well is agent did in its task and this is the value we try to maximize.<br>However, we don’t just try to maximize the immediate reward (the reward that our agent at the current state) the agent gets, we want to maximize the total sum of rewards that our agent, which includes the reward we get in the next step, and the rewards we are supposed to get at each time step till the end of the task.</p><p>The total sum of rewards the agent gets from the environment is called the <strong>return</strong>.<br>Mathematically, returns are expressed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/0*uALi3-7BvtstSFjN" /><figcaption>Return is the total sum of rewards from the current time step till the end</figcaption></figure><p>where:<br> <strong>Rₓ₊₁</strong> is the reward at time step <em>x</em>,<br> <strong>T</strong> is the final time step.</p><p>Or, you can express it as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/0*FWDS7VQAH8WR8cqd" /><figcaption>We terminate the summation at T-t-1 so that the last Reward the agent is to receive does not exceed R_T</figcaption></figure><p>It is simple to calculate the return on episodic tasks, you just add them up. But in continuous tasks, it is tricky. If you just add all the rewards, the return may even sum up to infinity!<br>This is where the discount rate comes in.</p><p>Return, with the discount rate (γ), reduces the importance of future rewards to our agent. This way, in a continuous task, the return never sums up to infinity.<br>Mathematically, it is expressed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/0*kUHzvZSn00DWRdSC" /><figcaption>Returns with the discount rate</figcaption></figure><p>OK, so by now you’ve seen what an agent is, how it interacts with its environment, what states, actions and rewards are, and how humans can be compared to RL agents.</p><p>But, the question might arise, <em>how does an agent decide what action to take in a particular state? and how does it evaluate how the agent will maximize the cumulative reward?</em></p><p>For us humans, our brain guides our decisions. It takes information about its surroundings and tells us to act accordingly.<br>Similarly, if we have a choice (and we always have a choice), it evaluates the goodness of all the possible choices and actions.</p><p>In a Reinforcement Learning agent, the answer is: <strong>Policy </strong>and <strong>Value</strong></p><h3>Policy</h3><blockquote>A <strong>policy</strong> (denoted by π) is a function that maps states to actions.<br><strong><em>π</em>(S) → A</strong></blockquote><p>A policy sometimes referred to as <strong>strategy, </strong>is a very important component of our RL agent, as this alone is sufficient to determine its behavior.</p><p>A policy is a function that tells our agent what action to take given its current state in the environment.</p><p>Generally denoted by the mathematical symbol <em>pi (π)</em>, a policy can be either <strong>deterministic</strong> or <strong>stochastic</strong>.</p><p>A deterministic policy returns the action to take at the current state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*vNdx5KuP4MaZZ_0yut-0jQ.png" /><figcaption>In a deterministic policy, action is returned</figcaption></figure><p>whereas, a stochastic policy returns the likelihood of taking an action in the current state to reach the goal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*BNFWO0P-XVmjeZydSmxcZA.png" /><figcaption>In a stochastic policy, a probability distribution over the action space is returned</figcaption></figure><p>The policy of an agent is continuously updated because one of the main aims of our agent is to find the <strong>optimal policy(π*)</strong>, the policy that maximizes the expected cumulative return.</p><h3>Value functions</h3><blockquote>A <strong>Value function</strong> is the expected cumulative discounted return our agent hopes from a particular state onwards.</blockquote><p>Positive and negative rewards are at the core of how an agent acts, and it’s only natural our agent will want to evaluate how “valuable” being in a state is.</p><p>The <em>value of a state</em> is the cumulative discounted return (Gₜ) our agent hopes to get starting from that state (sₜ), following a policy π, till the terminal state.</p><p>This kind of value function is called a <strong>state-value function </strong>or the<strong> v-function</strong>, which is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*gVhYBhcEpzLdPrYIhnF48Q.png" /><figcaption><strong>State-value function</strong> {𝔼 is the notation for “expected value of”; | is the notation for “given that”}</figcaption></figure><p>It is also possible our agent may want to assess the <em>quality of its action </em>in a state, following a policy π, starting from that time step till the end.</p><p>This kind of value function, that assesses the quality of the agent’s actions is called the <strong>action-value function </strong>or the<strong> Q-function </strong>(where q stands for ‘quality’).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yRixuScxd-OYz6YkRSlzHA.png" /><figcaption><strong>Action-value function</strong></figcaption></figure><p><em>Alright, so why are these value functions important?</em><br>These value functions are important because value functions are the key component when comparing two policies and/or finding an optimal policy.</p><p>Say for the current <em>sₜ</em>, there are two policies <strong>π</strong> and <strong>π</strong>’, then <strong>π</strong> is said to be better than <strong>π</strong>’ if:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/0*godKpJYk4V40TFqr" /><figcaption>A policy is better than another if its Q-Value is higher</figcaption></figure><p>Therefore, the optimal policy (the best policy that gives the most reward) has the highest Value function as compared to all the policies.</p><p>Policy and Value are also said to be a part of the <strong>RL agent’s brain</strong>. This is such because these two together do what a human brain does when we want to achieve a task; Policy makes decisions and decides the behavior of our agent, and the Value function evaluates the expected reward of the future, both of which are done by the <a href="https://www.thescienceofpsychotherapy.com/prefrontal-cortex/#:~:text=The%20prefrontal%20cortex%20(PFC)%20is%20the%20cerebral%20cortex%20covering%20the%20front%20part%20of%20the%20frontal%20lobe.%20This%20brain%20region%20has%20been%20implicated%20in%20planning%20complex%20cognitive%20behavior%2C%20personality%20expression%2C%20decision%20making%2C%20and%20moderating%20social%20behaviour">Prefrontal Cortex (PFC)</a> in a human brain.</p><h3>OK, but how do researchers train these Reinforcement Learning models?</h3><blockquote><strong>Reinforcement Learning is very data-hungry, it needs a lot of iterations, simulations, and time, to train itself.</strong></blockquote><p>There is a reason why a lot of the breakthroughs in Reinforcement Learning have happened on the gaming side, which has created so much of the buzz of Reinforcement Learning; training an RL agent to play a game is very easy, whereas training an RL agent to do things in the real world is not.</p><p>When training a Reinforcement Learning model to play a game, the environment is a game, meaning it doesn’t need to rest, just needs power. So, you can multiple games at the same time, or train the agent continuously by making it play the game again and again for days.</p><p>But what about training a model for the real world?</p><p>Do they just create a self-driving car and leave it in the real world? God no.<br>Reinforcement Learning is trial-and-error learning, and the error part will be a financial horror with a car.</p><p>They do, essentially, the same thing as when training to play games.<br>They simulate all the natural laws of physics, create different scenarios for the car (remember, <em>simulate</em> is the key here) in a game engine, like Unity. Not in the real world, but the training of an RL agent is done in a simulation of the real world.</p><p>What about the reward?<br>In a game, the reward is simple, maximize the score. But, what about real-world tasks? When does the agent get a reward?</p><p>In real-world tasks, a reward is given when the agent does what would be considered an achievement for a beginner (human) in that task.<br>This is because an RL agent also starts as a beginner, and this reward-motivated behavior is also central to a beginner learning to do a task, and become proficient at it.</p><p>Suppose, you need a reward for a self-driving car.<br>For someone learning how to drive, it is considered an achievement if he/she can go <em>x</em> kilometers without crashing the car. That also defines when the reward will be given to an RL agent.</p><blockquote><a href="https://www.nytimes.com/2011/02/17/science/17jeopardy-watson.html">“[IBM’s Watson] Wins on ‘Jeopardy!’: Trivial, it’s not”</a> — New York Times;</blockquote><blockquote>“<a href="https://www.theguardian.com/technology/2016/mar/15/googles-alphago-seals-4-1-victory-over-grandmaster-lee-sedol">AlphaGo seals 4–1 victory over Go grandmaster Lee Sedol</a>” — The Guardian;</blockquote><blockquote><a href="https://www.theverge.com/2019/4/13/18309459/openai-five-dota-2-finals-ai-bot-competition-og-e-sports-the-international-champion">“OpenAI’s Dota 2 AI steam rolls world champion e-sports team”</a> — The Verge;</blockquote><blockquote>The breakthroughs in <a href="https://www.youtube.com/watch?v=jeABMoYJGEU">robotic arm manipulation</a>;</blockquote><blockquote>Self-driving cars…</blockquote><p>These are all things achieved using Reinforcement Learning and its subfields (Deep RL, Multi-Agent RL, Imitation Learning, etc.); and, these are just a preview of things to come!</p><p>Since this topic resembles very closely how humans learn, this field is supposed to have enormous potential in deciding where AI will be headed in the future.</p><p>Thank you for reading the article till the end, hope you enjoyed it.</p><p>You know, I’m also in the Reinforcement Learning loop, to improve my writing.<br>So if you liked the article, please don’t forget to give it some claps 👏. If you didn’t like it, please give me some feedback so I can improve.<br>(And please be sure to do either, since how the environment responds is very important to the next step I take)</p><p>If you want to explore Reinforcement Learning more, check out the sources of this article.</p><h4>Sources:</h4><ol><li><a href="https://tomprof.stanford.edu/posting/1495">Tomorrow’s Professors’ Postings blog on “How do People learn?”</a></li><li><a href="https://towardsdatascience.com/hands-on-reinforcement-learning-course-part-1-269b50e39d08">Pau Labarta Bajo’s Hands-on Reinforcement Learning course</a></li><li><a href="https://www.youtube.com/watch?v=2pWv7GOvuf0">David Silver’s Introduction to Reinforcement Learning course</a></li><li><a href="https://web.stanford.edu/class/psych209/Readings/SuttonBartoIPRLBook2ndEd.pdf">Richard Sutton and Andrew Barto’s Reinforcement Learning book</a></li><li><a href="https://www.youtube.com/watch?v=0MNVhXEX9to">Steve Brunton: Reinforcement Learning</a></li><li><a href="http://rl-lab.com/">RL Lab</a></li><li><a href="https://www.youtube.com/watch?v=d5gaWTo6kDM">Andrew Ng’s CS229 Lecture 17</a></li><li><a href="https://lilianweng.github.io/lil-log/2018/02/19/a-long-peek-into-reinforcement-learning.html">Lilian Weng’s Blog on Reinforcement Learning</a></li></ol><h4>Notes:</h4><ol><li>Illustrations and Mathematical expressions with no source mentioned have been created by the author using <a href="https://www.canva.com/">Canva</a> and <a href="https://latex.codecogs.com/eqneditor/editor.php">CodeCogs</a>.</li></ol><p><em>Goodbye for now!<br>If you would like to reach out to me, or connect with me for inquiries and/or suggestions, feel free to find me on </em><a href="https://www.linkedin.com/in/utkarsh-malaiya/"><em>LinkedIn</em></a><em>, </em><a href="https://twitter.com/Utk_Mal_2707"><em>Twitter</em></a><em> or book a meeting with me using my </em><a href="https://calendly.com/malaiya-utkarsh/"><em>Calendly</em></a><em>.<br>Also, feel free to check out my </em><a href="https://utkmal.substack.com/welcome"><em>monthly newsletters</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a4a21a3da0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>