<?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 Cyborg on Medium]]></title>
        <description><![CDATA[Stories by Cyborg on Medium]]></description>
        <link>https://medium.com/@cyborgcodes?source=rss-8bbdf6236d18------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*t8Z6aM2QMGO8AtsPNmIe5A.jpeg</url>
            <title>Stories by Cyborg on Medium</title>
            <link>https://medium.com/@cyborgcodes?source=rss-8bbdf6236d18------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 06 Jul 2026 06:37:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cyborgcodes/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[Neural Style Transfer: Briefly explained and implemented in PyTorch.]]></title>
            <link>https://cyborgcodes.medium.com/neural-style-transfer-briefly-explained-and-implemented-in-pytorch-1edb45671c48?source=rss-8bbdf6236d18------2</link>
            <guid isPermaLink="false">https://medium.com/p/1edb45671c48</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[blog]]></category>
            <category><![CDATA[neural-style-transfer]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Cyborg]]></dc:creator>
            <pubDate>Sun, 26 May 2024 11:16:30 GMT</pubDate>
            <atom:updated>2024-05-26T11:16:30.913Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*0_06EgaOOQIuT5-kH68T6g.png" /></figure><h3>Brief History and Motivation Behind NST</h3><p>Neural Style Transfer (NST) is a technique that emerged from the intersection of deep learning and computer vision. It gained significant attention in 2015 when researchers Leon A. Gatys, Alexander S. Ecker, and Matthias Bethge introduced a groundbreaking paper titled “A Neural Algorithm of Artistic Style.” This paper showcased how convolutional neural networks (CNNs), which are typically used for image recognition tasks, could be repurposed to create stunning artistic images by blending the content of one image with the style of another.</p><p>You can read the published paper <a href="https://arxiv.org/abs/1508.06576">here</a>.</p><h3>What is Neural Style Transfer</h3><p>Neural Style Transfer is a deep learning technique that manipulates an image by merging the content of one image with the artistic style of another. Imagine taking a photograph of a cityscape and transforming it to look as if it were painted by Vincent van Gogh or Pablo Picasso. This is achieved by leveraging the power of CNNs to separately extract and recombine the content and style features of images.</p><p>The process works by first extracting the content features from the target image and the style features from the reference style image. Through an optimization process, NST adjusts a third image, called the generated image, to minimize the differences in content and style between the target and reference images respectively. The result is an image that maintains the structural integrity of the content image while adopting the stylistic elements of the reference image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e_GHBOBPGlyAFSQhqLpDDA.png" /></figure><h3>Understanding Content and Style in Images</h3><h4>Definition of Content and Style in the Context of Images</h4><p>In the context of image processing, “content” and “style” refer to two distinct aspects of an image.</p><ul><li><strong>Content:</strong> This pertains to the objects, structures, and the overall layout within an image. For example, in a photograph of a cityscape, the buildings, streets, and skyline represent the content. It captures the essence and the primary subjects of the image.</li><li><strong>Style: </strong>Style, on the other hand, encompasses the artistic elements of an image, such as colors, textures, brushstrokes, and patterns. In a painting, the style is what defines the artist’s unique approach, be it the swirling strokes of Van Gogh or the cubist forms of Picasso.</li></ul><h4>How Humans Perceive Content and Style Differently</h4><p>We humans have an innate ability to distinguish between content and style when viewing an image. This ability allows us to recognize the same scene (content) even when it is rendered in different artistic styles. For instance, a picture of a tree drawn in a cartoonish manner or painted realistically is still identifiable as a tree. Our brains can separate the structural components (content) from the aesthetic elements (style) seamlessly.</p><h4>The Role of Convolutional Neural Networks (CNNs) in Distinguishing Content from Style</h4><p>Convolutional Neural Networks (CNNs) play a pivotal role in the process of Neural Style Transfer by mimicking this human ability to separate content and style. CNNs are a class of deep learning models particularly adept at processing visual data. They are composed of multiple layers that extract features from images in a hierarchical manner.</p><ul><li><strong>Content Extraction: </strong>In the context of NST, deeper layers of a CNN are used to capture the content of an image. These layers respond to high-level features such as shapes and structures. By using these deeper layers, NST can effectively represent the primary subjects of an image without focusing on fine details.</li><li><strong>Style Extraction: </strong>The style of an image is captured using the responses from shallower layers of the CNN. These layers detect lower-level features like edges, textures, and colors. By examining the patterns of activation across these layers, NST can encode the stylistic elements of an image.</li></ul><p>The NST process involves optimizing a new image to have similar content representations (from the deeper layers) to the content image and similar style representations (from the shallower layers) to the style image. This optimization is done by minimizing a loss function that quantifies the differences in content and style between the generated image and the target images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WR5znTGQ964e-sZEGkSItw.png" /></figure><h3>Implementing Neural Style Transfer in PyT🔥rch</h3><h4>Step 1: Install and import required packages</h4><pre>!pip install torch torchvision torch_snippets<br><br># import the required packages<br>import torch<br>import torch.nn.functional as F<br>import torchvision.transforms as T<br>from torch_snippets import *<br><br># set the device<br>device = &quot;cuda:0&quot; if torch.cuda.is_available() else &quot;cpu&quot;<br>print(device)</pre><h4>Step 2: Load and preprocess the images</h4><pre># Url for the `style image`<br>!wget https://res.cloudinary.com/ezmonydevcloud/image/upload/v1710325675/turning-pattern.png<br><br># Url for the `content image`<br>!wget https://res.cloudinary.com/ezmonydevcloud/image/upload/v1710322208/thomas-shelby.jpg</pre><pre>preprocess = T.Compose([<br>    T.ToTensor(),<br>    # we&#39;ll use mean and std used for VGG models<br>    T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), <br>    T.Lambda(lambda x: x.mul_(255))<br>])<br><br>postprocess = T.Compose([<br>    T.Lambda(lambda x: x.mul(1./255)),<br>    T.Normalize(mean=[-0.485/0.229, -0.456/0.224, -0.406/0.225], std=[1/0.229, 1/0.224, 1/0.225]),<br>])</pre><h4><strong>Explanation</strong></h4><ul><li><strong>Preprocessing:</strong> Prepares the image data to match the distribution of the data used to train the VGG model. This involves normalizing the image tensor to have a specific mean and standard deviation, ensuring consistency in the input data.</li><li><strong>Postprocessing:</strong> Reverts the transformations applied during preprocessing, bringing the image data back to its original form or a form suitable for further use, such as visualization.</li></ul><pre>from PIL import Image<br>import matplotlib.pyplot as plt<br><br>imgs = [Image.open(path).resize((512, 512)).convert(&#39;RGB&#39;) for path in [&#39;turning-pattern.png&#39;, &#39;thomas-shelby.jpg&#39;]]<br>style_image, content_image = [preprocess(img).to(device)[None] for img in imgs]<br><br># Modify content image with `require_grad=True`<br>opt_img = content_image.data.clone()<br>opt_img.requires_grad = True</pre><pre># Display the images<br>fig, axes = plt.subplots(nrows=1, ncols=len(imgs), figsize=(len(imgs) * 5, 5))<br><br>for idx in range(len(imgs)):<br>    axes[idx].imshow(imgs[idx])<br>    axes[idx].axis(&#39;off&#39;) # do this, if you want to hide the axis<br>    <br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*EyyOBEiboK1ggRXCwyV63A.png" /></figure><h4>Step 3: Define the model class, <em>vgg19_modified</em></h4><pre>from torchvision.models import vgg19, VGG19_Weights<br><br>class vgg19_modified(nn.Module):<br>    def __init__(self):<br>        super().__init__()<br>        features = list(vgg19(weights=VGG19_Weights.IMAGENET1K_V1).features)<br>        self.features = nn.ModuleList(features).eval()<br>        <br>    # Define the forward method, which takes the list of layers and returns the features corresponding to each layer<br>    def forward(self, x, layers=[]):<br>        order = np.argsort(layers)<br>        _results, results = [], []<br>        for ix, model in enumerate(self.features):<br>            x = model(x)<br>            if ix in layers: _results.append(x)<br>        for o in order: results.append(_results[o])<br>        return results if layers is not [] else x<br>    <br># Define the model object<br>vgg = vgg19_modified().to(device)</pre><p>This code defines a modified VGG19 model that allows extraction of features from specific layers. By creating a custom vgg19_modified class, it loads the pre-trained VGG19, converts its feature layers to a ModuleList, and enables the forward method to return features from specified layers.</p><h4>Step 4: Implementing loss functions</h4><h4><strong>Content Loss Function</strong></h4><p>The content loss function is used to ensure that the generated image retains the primary subjects and structure of the content image. It measures how much the high-level features of the generated image differ from those of the content image.</p><p>In practice, this is achieved by passing both the content image and the generated image through a pre-trained Convolutional Neural Network (CNN) and extracting the feature maps from a specific layer. These feature maps represent the high-level content of the images.</p><p>The content loss <em>Lcontent</em>​ is calculated as the mean squared error (MSE) between the feature representations of the content image <em>P</em> and the generated image <em>G</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*JXCMewwtQ9JwgXQ_GchpUA.png" /><figcaption>content loss function visual representation</figcaption></figure><p>where:</p><ul><li><em>Fl</em> is the feature map of the generated image from layer <em>l</em>.</li><li><em>Pl</em> is the feature map of the content image from layer <em>l</em>.</li><li><em>i</em> and <em>j</em> index the elements in the feature maps.</li></ul><p>This loss function ensures that the generated image <em>G</em> has similar high-level features as the content image <em>P</em>, preserving the overall structure and objects in the scene.</p><h4>Style Loss Function</h4><p>The style loss function is designed to capture the stylistic elements of the style image and transfer them to the generated image. It measures how well the textures, colors, and patterns of the style image are replicated in the generated image.</p><p>To achieve this, the style of an image is represented using the Gram matrix, which captures the correlations between different feature maps in a layer of the CNN. The Gram matrix <em>Gl</em> for a layer <em>l</em> is defined as:​</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UuvY7fkBcxldIg_WfDanCw.png" /><figcaption>gram matrix representation</figcaption></figure><p>The style loss <em>Lstyle</em>​ is calculated as the MSE between the Gram matrices of the style image <em>S </em>and the generated image <em>P</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*MtXHHBmQH_5nGyEgSMjhag.png" /><figcaption>style loss function visual representation</figcaption></figure><p>This loss function ensures that the generated image <em>P</em> replicates the stylistic features of the style image <em>S,</em> including textures and patterns.</p><h4>Combining Content and Style Losses</h4><p>In Neural Style Transfer, the total loss function is a weighted sum of the content loss and the style loss:</p><p><em>Ltotal</em>​= <em>αLcontent</em>​+<em>βLstyle</em>​</p><p>where:</p><ul><li><em>α</em> and <em>β</em> are weights that control the relative importance of content and style.</li></ul><p>By minimizing this total loss function, the NST algorithm generates an image that balances the structure of the content image with the artistic style of the style image.</p><p><strong>Define the gram matrix module</strong></p><pre>class GramMatrix(nn.Module):<br>    def forward(self, input):<br>        b,c,h,w = input.size()<br>        feat = input.view(b, c, h*w)<br>        G = feat@feat.transpose(1,2)<br>        G.div_(h*w)<br>        return G<br>    <br># Define the gram matrix&#39;s corresponding MSE Loss, GramMSELoss<br>class GramMSELoss(nn.Module):<br>    def forward(self, input, target):<br>        out = F.mse_loss(GramMatrix()(input), target)<br>        return(out)</pre><p>Specify the layer that define content loss and style loss</p><pre>style_layers = [0, 5, 10, 19, 28]<br>content_layers = [21]<br>loss_layers = style_layers + content_layers<br><br># Define the loss function for content and style loss values<br>loss_fns = [GramMSELoss()] * len(style_layers) + [nn.MSELoss()] * len(content_layers)<br>loss_fns = [loss_fn.to(device) for loss_fn in loss_fns]<br><br># Define the weights associated with content and style loss<br>style_weights = [1000/n**2 for n in [64,128,256,512,512]]<br>content_weights = [1]<br>weights = style_weights + content_weights</pre><p>We need to manipulate our image such that the style of the target image resembles style_image as much as possible. Hence we compute the style_targets values of style_image by computing GramMatrix of features obtained from a few chosen layers of VGG. Since the overall content should be preserved, we choose the content_layer variable at which we compute the raw features from VGG.</p><pre>style_targets = [GramMatrix()(A).detach() for A in vgg(style_image, style_layers)]<br>content_targets = [A.detach() for A in vgg(content_image, content_layers)]<br>targets = style_targets + content_targets</pre><h4>Step 5: Define optimizer and number of iterations</h4><p>Even though we could have used Adam or any other optimizer, LBFGS is an optimizer that has been observed to work best in deterministic scenarios. Additionally, since we are dealing with exactly one image, there is nothing random. Many experiments have revealed that LBFGS converges faster and to lower losses in neural transfer settings, so we will use this optimizer</p><pre>max_iters = 1000<br>optimizer = optim.LBFGS([opt_img])<br>log = Report(max_iters)</pre><h4>Step 6: Train the model</h4><p>Perform the optimization. In deterministic scenarios where we are iterating on the same tensor again and again, we can wrap the optimizer step as a function with zero arguments and repeatedly call it, as shown here.</p><pre>iters = 0<br>while iters &lt; max_iters:<br>    def closure():<br>        global iters<br>        iters += 1<br>        optimizer.zero_grad()<br>        out = vgg(opt_img, loss_layers)<br>        layer_losses = [weights[a]*loss_fns[a](A,targets[a]) \<br>        for a,A in enumerate(out)]<br>        loss = sum(layer_losses)<br>        loss.backward()<br>        log.record(pos=iters, loss=loss, end=&#39;\r&#39;)<br>        return loss<br>    optimizer.step(closure)</pre><pre># Plot the variation in the loss<br>log.plot(log=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*dQoqFZzRgJ0VLWO1-1u9_g.png" /></figure><pre># Plot the image with combination of content and style images<br>out_img = postprocess(opt_img[0]).permute(1,2,0)<br>show(out_img)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*1tYh1B178lzW34r_kt8e_g.png" /></figure><p>As you can see our model after the training is successfully able to blend the style with the content of original image. You could try this out on your own images to test it out how it’s performing on those. You could also try out tweaking some parameters or training it for longer iterations, if you are not satisfied with the final result.</p><p>You could get the code on my <a href="https://www.kaggle.com/code/crownedhead06/neural-style-transfer-pytorch#Step-6:-Specify-the-layers-that-define-content-loss-and-style-loss">kaggle notebook</a>.</p><p>You could also try checking out my other blog posts:</p><ul><li><a href="https://medium.com/@cyborgcodes/what-is-early-stopping-in-deep-learning-eeb1e710a3cf">What is early stopping in deep learning?</a></li><li><a href="https://medium.com/@cyborgcodes/reinforcement-learning-101-best-introduction-for-beginners-b08c4b5e6b43">Reinforcement learning 101: Best introduction for beginners</a></li><li><a href="https://medium.com/@cyborgcodes/genetic-algorithm-implementation-code-from-scratch-in-python-160a7c6d9b96">Genetic algorithm implementation: Code from scratch in Python</a></li></ul><p>See you in future in a different dimension (maybe …)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1edb45671c48" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Genetic Algorithm Implementation: Code from scratch in Python]]></title>
            <link>https://cyborgcodes.medium.com/genetic-algorithm-implementation-code-from-scratch-in-python-160a7c6d9b96?source=rss-8bbdf6236d18------2</link>
            <guid isPermaLink="false">https://medium.com/p/160a7c6d9b96</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[genetic-algorithm]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Cyborg]]></dc:creator>
            <pubDate>Sun, 05 May 2024 18:27:58 GMT</pubDate>
            <atom:updated>2024-05-05T18:27:58.196Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*9gi2kSeufs_-coUe0s2FxQ.png" /></figure><p><strong>Genetic algorithms</strong> are a class of <a href="https://www.complexica.com/narrow-ai-glossary/optimization-algorithms">optimization algorithms</a> inspired by the process of <a href="https://en.wikipedia.org/wiki/Natural_selection">natural selection</a>. They are used to find approximate solutions to optimization and search problems. GAs are based on the principles of genetics and evolution, such as inheritance, mutation, selection, and crossover (recombination).</p><h3>How Genetic Algorithms Work</h3><p>Genetic Algorithms work by mimicking the process of natural selection and evolution to find approximate solutions to optimization and search problems. Here’s a step-by-step explanation of how they work:</p><h4>Step 1️⃣: Initialization</h4><p>Genetic algorithms begin by creating a population of random candidate solutions, known as chromosomes, to represent potential solutions to the problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5V2P2H4sHjuEmr-TTWWoLA.png" /><figcaption>Initialising a population of 10 chromosomes</figcaption></figure><p>In above code, each chromosome is a binary representation of an integer ranging between 0–255. As closer their value is to a <strong><em>threshold</em></strong> (we will define) as better that chromose is for our current scenario.</p><h4>Step 2️⃣: Selection</h4><p>The fitness of each chromosome is evaluated based on how well it solves the problem. The fittest chromosomes are selected to serve as parents for the next generation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*-L1go-pdXXwuz6ePPjd7Pw.png" /><figcaption>fitness function to test each chromosome</figcaption></figure><p>As closer the<strong><em> fitness score</em></strong> of a chromosome is to 255 as likely they would be selected to serve as parents for the up coming generations (and its only possible when their integer representation is close to <strong><em>threshold</em></strong>).</p><h4>Step 3️⃣: Crossover</h4><p>Selected parents are used to create new offspring through a process called crossover, where genetic material from two parents is combined to produce one or more offspring.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WiO9GGl8K3Ww8ep1A_Jy_g.png" /></figure><p>New born childs/chromosomes would have combined genes of both parents as we see in any human child.</p><h4>Step 4️⃣: Mutation</h4><p>To maintain genetic diversity in the population, random changes, or mutations, are introduced to the offspring’s genetic material.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gsBYsOTLlpfxV0vef7a5Ig.png" /></figure><p>Mutation makes sure that each child would maintain diversity from each other and parents altogether.</p><h4>Step 5️⃣: Replacement</h4><p>The least fit members of the population are replaced by the new offspring, ensuring that the population evolves towards better solutions over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*dE6B6RE__nJ0YmGlw0SaYA.png" /><figcaption>Replacement of population (offsprings taking place of old chromosomes)</figcaption></figure><h4>Step 6️⃣: Termination</h4><p>The process is repeated for multiple generations until a termination condition is met, such as finding an acceptable solution or reaching a maximum number of generations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GdMvzFbK5VC544-7i1DpHw.png" /></figure><p>In most scenarios you would notice the best chromosome until the last generation has reached the best fitness score.</p><p>Genetic algorithms are widely used in optimization and search problems across various domains. They are particularly useful when the search space is large and complex.</p><p>You would see genetic algorithms (along with neural networks) widely being used in developing ai agents to play various games like flappy bird, snake, ping pong and many other single &amp; multi player games.</p><p>In my next blog, I will guide you through how to use neural networks along with genetic algorithms to create such agents. This technique is called <a href="https://en.wikipedia.org/wiki/Reinforcement_learning"><strong>NEAT (NeuroEvolution of Augmenting Topologies).</strong></a> I think you might have heard about it before, if you have dived well enough in the field of <a href="https://en.wikipedia.org/wiki/Reinforcement_learning">reinforcement learning</a>.</p><p>🧑🏻‍💻 <a href="https://github.com/cyb0rg14/DeepLearning/blob/master/scratch/genetic-algorithm.py">Code your own genetic algorithm from scratch using python</a></p><p>👨🏻‍🔬 <a href="https://www.youtube.com/watch?v=XP2sFzp2Rig">Genetic algorithms explained (but this time visually)</a></p><p>If you’d like to learn more about genetic algorithms or reinforcement learning in general, then don’t forget to follow my page. See ya’ 👋🏻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=160a7c6d9b96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reinforcement Learning 101: Best Introduction for Beginners]]></title>
            <link>https://cyborgcodes.medium.com/reinforcement-learning-101-best-introduction-for-beginners-b08c4b5e6b43?source=rss-8bbdf6236d18------2</link>
            <guid isPermaLink="false">https://medium.com/p/b08c4b5e6b43</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Cyborg]]></dc:creator>
            <pubDate>Thu, 18 Apr 2024 15:22:41 GMT</pubDate>
            <atom:updated>2024-05-01T06:51:08.746Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*dowC-bFRUhC6q6M-1Yem4g.png" /></figure><p>Reinforcement learning is a <strong>framework for solving control tasks</strong> <strong>(also called decision problems)</strong> by building agents that learn from the environment by interacting with it through trial and error and <strong>receiving rewards (positive or negative) as unique feedback.</strong></p><p><em>I know this definition can be intimidating at first, so I will try to explain this definition to you with a real world example:</em></p><ul><li>Imagine putting your little brother in front of a video game he never played, giving him a controller, and leaving him alone.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*pi4R618aJb56B1RlVDsoiw.png" /></figure><ul><li>Your brother will interact with the environment (the video game) by pressing the right button (action). He got a coin, that’s a +1 reward. It’s positive, he just understood that in this game he must <strong>get the coins.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*QuANLGRVkx99rCVj8unftQ.png" /></figure><ul><li>But then, <strong>he presses the right button again</strong> and he touches an enemy. He just died, so that’s a -1 reward.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*3mhHX3nxYB63ODLZVKP9dg.png" /></figure><p>By interacting with his environment through trial and error, your little brother understands that <strong>he needs to get coins in this environment but avoid the enemies.</strong></p><p><strong>Without any supervision</strong>, the child will get better and better at playing the game.</p><p>That’s how humans and animals learn, <strong>through interaction.</strong> Reinforcement Learning is just a <strong>computational approach of learning from actions.</strong></p><h3>The reward hypothesis: the central idea of Reinforcement Learning</h3><p>⇒ Why is the goal of the agent to maximize the expected return?</p><p>Because RL is based on the <strong>reward hypothesis</strong>, which is that all goals can be described as the <strong>maximization of the expected return</strong> (expected cumulative reward).</p><p>That’s why in Reinforcement Learning, <strong>to have the best behavior,</strong> we aim to learn to take actions that <strong>maximize the expected cumulative reward.</strong></p><h3>THE RL PROCESS:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bks55MKmhpkJkbSYzdDWYw.jpeg" /><figcaption>Reinforcement Learning Process</figcaption></figure><ul><li>Our Agent receives state S0​ from the Environment — we receive the first frame of our game (Environment).</li><li>Based on that state S0​, the Agent takes action A0 — our Agent will move to the right.</li><li>The environment goes to a new state S1 — new frame.</li><li>The environment gives some reward R1​ to the Agent — we’re not dead <em>(Positive Reward +1)</em>.</li></ul><p>This RL loop outputs a sequence of state, action, reward and next state.</p><p><strong><em>Now time has come for you to understand all the common jargons used in Reinforcement Learning world. You can narrow your focus on screen now.</em></strong></p><h3>Observations/States Space:</h3><p>Observations/States are the <strong>information our agent gets from the environment.</strong> In the case of a video game, it can be a frame (a screenshot). In the case of the trading agent, it can be the value of a certain stock, etc.</p><p>There is a differentiation to make between <em>observation</em> and <em>state</em>, however:</p><ul><li><em>State s</em>: is <strong>a complete description of the state of the world</strong> (there is no hidden information). In a fully observed environment.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*Cqi-7JKQUepB-KIfT-Yl4Q.png" /><figcaption>In a chess game, we have access to the whole board information, so we receive a state from the environment. In other words, the environment is fully observed.</figcaption></figure><ul><li><em>Observation o</em>: is a partial description of the state. In a partially observed environment.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*_sXwdp2ZATItkZY5pGyHMQ.png" /><figcaption>In Super Mario Bros, we only see the part of the level close to the player, so we receive an observation.</figcaption></figure><p>In Super Mario Bros, we are in a partially observed environment. We receive an observation <strong>since we only see a part of the level.</strong></p><h3>Action Space</h3><p>The Action space is the set of <strong>all possible actions in an environment.</strong></p><p>The actions can come from a <em>discrete</em> or <em>continuous space</em>:</p><ul><li><em>Discrete space</em>: the number of possible actions is <strong>finite</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*_sXwdp2ZATItkZY5pGyHMQ.png" /><figcaption>In Super Mario Bros, we have only 4 possible actions: left, right, up (jumping) and down (crouching).</figcaption></figure><p>Again, in Super Mario Bros, we have a finite set of actions since we have only 4 directions.</p><ul><li><em>Continuous space</em>: the number of possible actions is <strong>infinite</strong>.</li></ul><figure><img alt="A Self Driving Car agent has an infinite number of possible actions since it can turn left 20°, 21,1°, 21,2°, honk, turn right 20°…" src="https://cdn-images-1.medium.com/max/1024/1*N0_m2MzdvZIOssCAA2upsw.png" /></figure><h3>Rewards and the Discounting</h3><p>The reward is fundamental in RL because it’s <strong>the only feedback</strong> for the agent. Thanks to it, our agent knows <strong>if the action taken was good or not.</strong></p><p>The cumulative reward at each time step <strong>t</strong> can be written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r8ug-d1BHnDhk9bBnIJbTQ.png" /><figcaption>The cumulative reward equals the sum of all rewards in the sequence.</figcaption></figure><p>However, in reality, <strong>we can’t just add them like that.</strong> The rewards that come sooner (at the beginning of the game) <strong>are more likely to happen</strong> since they are more predictable than the long-term future reward.</p><p>Let’s say your agent is this tiny mouse that can move one tile each time step, and your opponent is the cat (that can move too). The mouse’s goal is <strong>to eat the maximum amount of cheese before being eaten by the cat.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EXFYbEmU7vGy-nrwQldmXA.jpeg" /></figure><p>As we can see in the diagram, <strong>it’s more probable to eat the cheese near us than the cheese close to the cat</strong> (the closer we are to the cat, the more dangerous it is).</p><p>Consequently, <strong>the reward near the cat, even if it is bigger (more cheese), will be more discounted</strong> since we’re not really sure we’ll be able to eat it.</p><p>To discount the rewards, we proceed like this:</p><ol><li>We define a discount rate called gamma. <strong>It must be between 0 and 1.</strong> Most of the time between <strong>0.95 and 0.99</strong>.</li></ol><ul><li>The larger the gamma, the smaller the discount. This means our agent <strong>cares more about the long-term reward.</strong></li><li>On the other hand, the smaller the gamma, the bigger the discount. This means our <strong>agent cares more about the short term reward (the nearest cheese).</strong></li></ul><p>2. Then, each reward will be discounted by gamma to the exponent of the time step. As the time step increases, the cat gets closer to us, <strong>so the future reward is less and less likely to happen.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SZoXv0IYmFupZ5-mrgc0pA.png" /></figure><h3>Type of Tasks</h3><p>A task is an <strong>instance</strong> of a Reinforcement Learning problem. We can have two types of tasks: <strong>episodic</strong> and <strong>continuing</strong>.</p><h4>Episodic task</h4><p>In this case, we have a starting point and an ending point <strong>(a terminal state). This creates an episode</strong>: a list of States, Actions, Rewards, and new States.</p><p>For instance, think about Super Mario Bros: an episode begin at the launch of a new Mario Level and ends <strong>when you’re killed or you reached the end of the level.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*_sXwdp2ZATItkZY5pGyHMQ.png" /><figcaption>Beginning of a new episode</figcaption></figure><h4>Continuing tasks</h4><p>These are tasks that continue forever (<strong>no terminal state</strong>). In this case, the agent must <strong>learn how to choose the best actions and simultaneously interact with the environment.</strong></p><p>For instance, an agent that does automated stock trading. For this task, there is no starting point and terminal state. <strong>The agent keeps running until we decide to stop it.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*l9fWjXgsG8x1fU_qAJhslg.jpeg" /></figure><h3>The Exploration/Exploitation trade-off</h3><p>Finally, before looking at the different methods to solve Reinforcement Learning problems, we must cover one more very important topic: <em>the exploration/exploitation trade-off.</em></p><ul><li><em>Exploration</em> is exploring the environment by trying random actions in order to <strong>find more information about the environment.</strong></li><li><em>Exploitation</em> is <strong>exploiting known information to maximize the reward.</strong></li></ul><p>Remember, the goal of our RL agent is to maximize the expected cumulative reward. However, <strong>we can fall into a common trap</strong>.</p><p>Let’s take an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5nL2QnIqbdmcU6LxUIVwRg.jpeg" /></figure><p>In this game, our mouse can have an <strong>infinite amount of small cheese</strong> (+1 each). But at the top of the maze, there is a gigantic sum of cheese (+1000).</p><p>However, if we only focus on exploitation, our agent will never reach the gigantic sum of cheese. Instead, it will only exploit <strong>the nearest source of rewards,</strong> even if this source is small (exploitation).</p><p>But if our agent does a little bit of exploration, it can <strong>discover the big reward</strong> (the pile of big cheese).</p><p>This is what we call the exploration/exploitation trade-off. We need to balance how much we <strong>explore the environment</strong> and how much we <strong>exploit what we know about the environment.</strong></p><p>Therefore, we must <strong>define a rule that helps to handle this trade-off</strong>. We’ll see the different ways to handle it in the future units.</p><p>If it’s still confusing, <strong>think of a real problem: the choice of picking a restaurant:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cheaXBlNAvcvDyWxPip-zw.png" /></figure><ul><li><em>Exploitation</em>: You go to the same one that you know is good every day and <strong>take the risk to miss another better restaurant.</strong></li><li><em>Exploration</em>: Try restaurants you never went to before, with the risk of having a bad experience <strong>but the probable opportunity of a fantastic experience.</strong></li></ul><h3>Two main approaches for solving RL problems</h3><p>Now that we learned the RL framework, how do we solve the RL problem?</p><p>In other words, how do we build an RL agent that can <strong>select the actions that maximize its expected cumulative reward?</strong></p><h4>The Policy π: the agent’s brain</h4><p>The Policy <strong>π</strong> is the <strong>brain of our Agent</strong>, it’s the function that tells us what <strong>action to take given the state we are in.</strong> So it <strong>defines the agent’s behavior</strong> at a given time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*I2Urbtl_JIPnXkcGqtez4Q.png" /></figure><p>This Policy <strong>is the function we want to learn</strong>, our goal is to find the optimal policy π*, the policy that <strong>maximizes expected return</strong> when the agent acts according to it. We find this π* <strong>through training.</strong></p><p>There are two approaches to train our agent to find this optimal policy π*:</p><ul><li><strong>Directly,</strong> by teaching the agent to learn which <strong>action to take,</strong> given the current state: <strong>Policy-Based Methods.</strong></li><li>Indirectly, <strong>teach the agent to learn which state is more valuable</strong> and then take the action that <strong>leads to the more valuable states</strong>: Value-Based Methods.</li></ul><h4>Policy-Based Methods</h4><p>In Policy-Based methods, <strong>we learn a policy function directly.</strong></p><p>This function will define a mapping from each state to the best corresponding action. Alternatively, it could define <strong>a probability distribution over the set of possible actions at that state.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F1btD4VBjq66HAz_hzngOg.jpeg" /></figure><p>We have two types of policies:</p><ul><li><em>Deterministic</em>: a policy at a given state <strong>will always return the same action.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*s_NZyHAE2BQq16jmhclTHA.jpeg" /><figcaption>action = policy(state)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*Yaw0uCoQf1HFjVhu_ETVsw.jpeg" /></figure><ul><li><em>Stochastic</em>: outputs a <strong>probability distribution over actions.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*zt33Yk5R4r4xMLTm46tuQQ.png" /><figcaption>policy(actions | state) = probability distribution over the set of actions given the current state</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y8o17gdqUdpxy0Ko2EJ0ZA.png" /><figcaption>Given an initial state, our stochastic policy will output probability distributions over the possible actions at that state.</figcaption></figure><h4>Value-based methods</h4><p>In value-based methods, instead of learning a policy function, we <strong>learn a value function</strong> that maps a state to the expected value <strong>of being at that state.</strong></p><p>The value of a state is the <strong>expected discounted return</strong> the agent can get if it <strong>starts in that state, and then acts according to our policy.</strong></p><p>“Act according to our policy” just means that our policy is <strong>“going to the state with the highest value”.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*fJwD6uMI-SGmzcLxPO8zDA.png" /></figure><p>Here we see that our value function <strong>defined values for each possible state.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wqiFCC7kERiI1W_gm71JMQ.jpeg" /></figure><p>Thanks to our value function, at each step our policy will select the state with the biggest value defined by the value function: -7, then -6, then -5 (and so on) to attain the goal.</p><p><em>I understand that some of this might have been a bit confusing, but I don’t want you to feel overwhelmed. Let’s clear things up together! Here’s a simple breakdown of everything we’ve talked about.</em></p><ul><li><strong>Reinforcement Learning</strong> is all about maximizing the <strong>cumalative reward/expected return</strong> by optimizing the<strong> Policy π (the agent’s brain).</strong></li><li>You could also understand it like this: when training <strong>neural networks</strong>, our goal has to minimize the <strong>loss function</strong> by optimizing the <strong>weights.</strong></li><li>To optimize the policy, we have two options. First, by using <strong>policy based methods</strong> which optimize the <strong>policy directly.</strong> And second,<strong> value based methods</strong> which <strong>indirectly</strong> helps optimizing the policy.</li><li>And ultimately all reinforcement learning revolves around <strong>agent, states, actions </strong>and<strong> rewards.</strong></li></ul><p>By now, I hope you’ve grasped the essence of reinforcement learning and even picked up on some of the jargon commonly used in this field. If you’re eager to dive deeper into the world of reinforcement learning, here are some resources to help you along the way 👇</p><h3>Books:</h3><ul><li><a href="https://github.com/cyb0rg14/DeepLearning/blob/master/book/reinforcement-learning-an-introduction-2nd-edition.pdf">Reinforcement Learning: An Introduction</a></li><li><a href="https://github.com/cyb0rg14/DeepLearning/blob/master/book/grokking-deep-reinforcement-learning.pdf">Grokking Deep Reinforcement Learning</a></li></ul><p>These two are my personal best books. First book, explains reinforcement learning theories whereas second books teaches you to code algorithms from scratch to solidify your knowledge.</p><p>Additional course you could take (not a book): <a href="https://huggingface.co/learn/deep-rl-course/en/unit0/introduction">Deep Reinforcement Learning course</a> by Hugging face community.</p><p><strong>Note:</strong> <em>This blog is highly inspired by the introduction chapeter of the above course. If you liked this blog, I would highly recommend you to take this course.</em></p><h3>Youtube Playlists:</h3><ul><li><a href="https://youtube.com/playlist?list=PLYgyoWurxA_8ePNUuTLDtMvzyf-YW7im2&amp;si=WnVNyK66Az-vMvhn">Reinforcement Learning course</a> by CIS 522</li><li><a href="https://www.youtube.com/playlist?list=PLTl9hO2Oobd9kS--NgVz0EPNyEmygV1Ha">Reinforcement Learning 101</a> by CodeEmporium</li><li><a href="https://youtube.com/playlist?list=PLqYmG7hTraZDVH599EItlEWsUOsJbAodm&amp;si=Cg6A6A5Ex7WbT0XC">Reinforcement Learning series </a>by DeepMind x UCL</li></ul><p><strong>Note: </strong><em>I haven’t watched many youtube videos on reinforcement learning, these are the best playlists I’ve come around so far. You could also search for better tutorials on yourselves.</em></p><p>If you’ve come to the end and liked reading this blog, you could show me your appreciation by giving me round of applause. And yeah definitely, you could follow me for more<strong> reinforcement learning related blogs</strong> (or in general for <strong>Deep Learning</strong>)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b08c4b5e6b43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Early Stopping in Deep Learning?]]></title>
            <link>https://cyborgcodes.medium.com/what-is-early-stopping-in-deep-learning-eeb1e710a3cf?source=rss-8bbdf6236d18------2</link>
            <guid isPermaLink="false">https://medium.com/p/eeb1e710a3cf</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[overfitting]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Cyborg]]></dc:creator>
            <pubDate>Fri, 05 Apr 2024 11:39:31 GMT</pubDate>
            <atom:updated>2024-04-05T11:39:31.447Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*rgY5zlyirCXoY_MkUYHBNQ.png" /></figure><p><strong>Early stopping </strong>is a technique used while training neural networks to prevent the model from overfitting. <em>Before understanding what actually early stopping is, you must know what is overfitting.</em></p><h3>What is Overfitting?</h3><p>Overfitting is a common problem in machine learning and deep learning where a model learns the training data too well. It happens when the model captures not only the underlying patterns in the data but also the noise or random fluctuations. As a result, the model performs exceptionally well on the training data but poorly on unseen data (test data or real-world data).</p><h4>Causes of Overfitting:</h4><ol><li><strong>Complex Model:</strong> Using a model with too many parameters relative to the number of observations can lead to overfitting. The model might capture the noise in the training data, making it perform poorly on new data.</li><li><strong>Insufficient Training Data</strong>: If the dataset is too small, the model might not have enough examples to learn the underlying patterns effectively. It might end up learning the noise in the data.</li><li><strong>Lack of Regularization:</strong> Regularization techniques, such as L1 and L2 regularization, add a penalty to the loss function to prevent the model from fitting the training data too closely. Without these, the model might overfit.</li></ol><p>There are few more causes that could lead to overfitting including <strong>data leakage </strong>and<strong> overly optimisic evaluation metrics.</strong></p><h4>Preventing the model from overfitting involves following techniques:</h4><ol><li>Use More Data</li><li>Regularization</li><li>Dropout</li><li><strong>Early Stopping</strong></li><li>Data Augmentation</li></ol><p>And there are still many other ways to prevent overfitting. But in this blog, I would specifically explain about <strong>‘Early Stopping’.</strong></p><h3>What is Early Stopping?</h3><p>Early stopping is a form of regularization used to prevent overfitting in machine learning and deep learning models. It involves stopping the training process before the model starts to overfit. The idea is to monitor the model’s performance on a validation set during the training process and stop training when the performance starts to degrade, which is an indication that the model is beginning to overfit the training data.</p><figure><img alt="Graph representing early stopping in a neural network" src="https://cdn-images-1.medium.com/max/1024/1*-37i5H3lie_x5299utHX4A.png" /></figure><h4>How Early Stopping Works</h4><ol><li><strong>Validation Set: </strong>During training, a portion of the training data is set aside as a validation set. This set is used to evaluate the model’s performance at each epoch (iteration over the entire dataset).</li><li><strong>Performance Monitoring:</strong> The model’s performance on the validation set is monitored at each epoch. Common metrics used for this purpose include accuracy, loss, or any other metric relevant to the problem at hand.</li><li><strong>Early Stopping Criterion:</strong> If the performance on the validation set starts to degrade (e.g., the loss increases or the accuracy decreases), it’s an indication that the model is beginning to overfit the training data. At this point, early stopping is triggered, and the training process is halted.</li><li><strong>Model Selection: </strong>Since the training is stopped before overfitting occurs, the model at the point of early stopping is typically the best model, as it has not yet learned the noise in the training data</li></ol><h4>How does early stopping works in the code</h4><p>To be honest, this is all there is to early stopping. Before finishing this blog, I would like to show you, how to implement early stopping in <strong>PyTorch.</strong></p><pre>import torch<br>import torch.nn as nn<br>import torch.optim as optim<br>from torch.utils.data import DataLoader<br>from torchvision import datasets, transforms<br><br># Define your model, loss function, and optimizer<br>model = ...<br>criterion = nn.CrossEntropyLoss()<br>optimizer = optim.SGD(model.parameters(), lr=0.01)<br><br># Load your data<br>train_data = datasets.MNIST(...)<br>train_loader = DataLoader(train_data, batch_size=64, shuffle=True)<br><br># Early stopping parameters<br>patience = 5 # Number of epochs to wait before stopping<br>min_delta = 0.01 # Minimum change in loss to qualify as an improvement<br>patience_counter = 0<br>best_loss = float(&#39;inf&#39;)<br><br>for epoch in range(100): # Maximum number of epochs<br>    running_loss = 0.0<br>    for inputs, labels in train_loader:<br>        # training logic here<br><br>    # Validation<br>    val_loss = ... # Calculate validation loss<br><br>    # Check for improvement<br>    if val_loss &lt; best_loss - min_delta:<br>        best_loss = val_loss<br>        patience_counter = 0<br>    else:<br>        patience_counter += 1<br>        if patience_counter &gt;= patience:<br>            print(f&quot;Early stopping at epoch {epoch}&quot;)<br>            break<br><br>print(f&quot;Best validation loss: {best_loss}&quot;)</pre><p>In this example, we’re using a simple model and a placeholder for the validation loss calculation. You’ll need to replace this with your actual validation loss calculation. The key part is the early stopping logic, which checks if the validation loss has improved by at least min_delta from the best loss seen so far. If not, it increments paitence_counter. If patience_counter reaches the patience value, training is stopped.</p><p>Remember, early stopping is a form of regularization and is particularly useful when you have a validation set to monitor the model’s performance on unseen data.</p><p><strong><em>If you’ve liked the explanation, you could show your appreciation by giving me a round of applause. And if you would like to understand other ways to prevent overfitting, you could comment below </em>👇</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eeb1e710a3cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>