<?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 Arnav Dantuluri on Medium]]></title>
        <description><![CDATA[Stories by Arnav Dantuluri on Medium]]></description>
        <link>https://medium.com/@arnavdantuluri?source=rss-d6494070acd5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*dQx7xQZ_FmXfhkEV</url>
            <title>Stories by Arnav Dantuluri on Medium</title>
            <link>https://medium.com/@arnavdantuluri?source=rss-d6494070acd5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 08:19:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arnavdantuluri/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[Learned Data Augmentation using VQ-Vae]]></title>
            <link>https://medium.com/@arnavdantuluri/learned-data-augmentation-using-vq-vae-339a8e12b779?source=rss-d6494070acd5------2</link>
            <guid isPermaLink="false">https://medium.com/p/339a8e12b779</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[vae]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[generative-model]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <dc:creator><![CDATA[Arnav Dantuluri]]></dc:creator>
            <pubDate>Sun, 01 May 2022 23:55:26 GMT</pubDate>
            <atom:updated>2022-05-02T06:14:36.884Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Abstract:</strong></p><p><strong>In this paper, I propose a simple and easily reproducible method to enhance and extend datasets from as few as 1000 images to as much as 10000 or in essence as many as the user requires. My approach combines a proper latent space modeling of the VAE which is then modified using a process called vector quantization. With these techniques along with enhancing model parameterization and training a simple convolutional neural network can achieve accuracies of up to 93% on synthetic data which proves extremely helpful especially when handling datasets with very few images.</strong></p><p><strong>Introduction:</strong></p><p>Machine learning is one of the largest and fastest-growing fields in computer science and is also one of the most data-intensive fields with industry-acceptable models requiring close to an excess of millions of images. Models like GPT-3 and BERT which are the current flagships for natural language processing were trained on hundreds of billions of words with BERT-Base taking over 4 days to train on 4 TPUs[1], keep in mind that TPUs are specifically built to train machine learning models, in comparison, it can take over 7 days to train BERT-Base on 8 gpus[2]. The main takeaway is that machine learning models require extremely large amounts of data and a long time to train. The time factor of machine learning cannot be easily overcome without improvements in hardware or cloud computing or additional computational libraries such as JAX which can significantly speed up matrix calculations and the data factor can be tackled using linear transformations such as crops, resizes, or random noise generation. While these methods are effective in their own right they do not tackle the inherent problem of a lack of data. Linear transformations are the same image just modified to a certain extent providing no real advantage to the lack of data; they just provide a solution to the problem of overfitting. To tackle the problem of data, researchers have been trying methods of learned data augmentation for years[3][4] however most of these methods utilize generative adversarial neural networks which requires a ton of computational resources or utilize a variational autoencoder which is not a effective as vq-vaes at making meaningful representations from the latent space. Visuals differences will be discussed towards the end of the paper.</p><p><strong>Variational Autoencoders:</strong></p><p>Variational autoencoders were first introduced in 2013[5] by Diederik P. Kingma and Max Welling. Variational Autoencoders attempt to reproduce the original X data from a Z or a latent space that exists in a lower-dimensional space than that of the original data. It is compressed by the Encoder the equation which can be written by,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/0*SadzBT0yvlz97HCU" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/0*t3MGK7Rx3DhLvSby" /></figure><p>where represents the sample distribution often represented as either a Gaussian noise or a Bernoulli distribution. The decoder is another neural net. Its input is the representation z, it outputs the parameters to the probability distribution of the data, and has weights and biases <em>ϕ</em>. Taking for example the mnist dataset, let’s say the handwritten number images are black and white and represent each pixel as 0 or 1. The probability distribution of a single-pixel can be then represented using a Bernoulli distribution. The decoder gets as input the latent representation of a digit <em>z</em> and outputs 784 (in the case of 28x28 images) Bernoulli parameters, one for each of the 784 pixels in the image. The decoder then takes in the latent space and tries to return the latent space to the original data that was passed into the encoder but because all the data cannot be contained within the reduced/compressed data the decoder often produces certain variations in the reconstructed image which in this case is extremely favorable due to the need for increased data.</p><p><strong>Vector Quantised Variational Autoencoders:</strong></p><p>Vector Quantised variational autoencoders or VQ-VAE’s for short were first introduced in 2013[6] in a paper titled “Neural Discrete Representation Learning”. VQ-Vae provides multiple advantages over methods such as basic Variational Autoencoders or even GANs in the sense that the use of a VQ-Vae would prevent “posterior collapse” a phenomenon that occurs due to an extremely powerful decoder in the Vae causing certain latents to be ignored. This poses a major problem especially when dealing with data generations because the ignored latents cause data to be lost forming an incorrect image from the latent space. To explain the magnitude of this issue let’s take an example. In the case of medical imaging (CT scans, pneumonia identification, etc.) if the decoder suffers from posterior collapse it becomes useless as a means to produce meaningful representations of the data. This could pose a major issue, especially for medical data when the accuracy of the model could save a patient’s life meaning the data the model reproduces must be accurate enough to allow an identifier model, such as a convolutional neural network, to be able to replicate that accuracy. However, VQ-Vaes’ utilize a discrete latent space which leads to the issue of running backpropagation with the model not being able to run back propagations through the latent space. This issue is resolved by using a method called straight to gradient which copies the gradients over from the decoder to the encoder thereby bypassing the “codebook” vector that the VQ-Vae produces. As aforementioned, this is what produces the error with backpropagation as the latent space is non-differentiable and gradients cannot be pushed through the bottleneck which is resolved with the previously mentioned process by copying gradients over.</p><p><strong>Experiments Run:</strong></p><p>To explore how much of an advantage a VQ-VAE really has over other models such as a GAN or a VAE I trained each variation of the most popular generator models to serve as a baseline to compare to the VQ-VAE. Let’s delve into the results</p><p>The results produced by a deep convolutional generative adversarial neural network (DCGAN). Utilizes Convolutional neural networks for better image classification by the discriminator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*QIWnCm7E0cRjHevu" /></figure><p>Results after 25 epochs (baseline no of epochs for each model)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*kMHPAeTMKvnpIJKd" /></figure><p>Results after 550 epochs of training.</p><p>These results truly illustrate how costly it is to implement a generative adversarial network that can produce meaningful data representations. It would take approximately 5000 epochs to produce images that even closely resemble that of the original data which is not taking into account the amount of data that we have access to.</p><p>Results produced after 25 epochs of training for a variational autoencoder. Not bad but not nearly a adequate representation to deal with the data deficit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/0*os6r4jN_mC1xuGG7" /></figure><p>Now for the vector quantized variational autoencoder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/0*sCCwADAR-y4xm-3H" /></figure><p>The results after 30 epochs of training. Absolutely stunning. It was able to produce a representation that almost replicated the model directly except for a little noise in the reconstructed image. Let’s take a look at another example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*1F8MfX4FPGYNrl3L" /></figure><p>While this is truly amazing we do need to test the method further. Creating a meaningful representation from numeric values with little to no complexity cannot be compared to the complexity of an image such as a brain or a CT scan of human lungs . So let’s test the method further with the pneumonia dataset from kaggle[7].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/0*QKL0JCwOz4M6lIxO" /></figure><p>Pretty good, especially for only 500 epochs. Also important to consider the fact that the original representation also was quite noisy meaning the reconstructed image might be less accurate but the representation does contain the important features as the original image. It would be much better if we ran the model for 5000 epochs or 10000 but considering the wide array of use cases it might be better to let the model train for 430,000 updates as Dall-E was trained for including of course higher computationally effective devices such as GPUs and TPUs. The deconstructed image and the latent space showing how powerful the encoder network is after only 500 epochs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/0*YuVWWgXCuNhfT8Sd" /></figure><p>As an experiment I wanted to utilize a dataset with a wide variety of scenes and lighting effects[8] to see if maybe the model might reconstruct an image with major differences caused because of the wide variety of images between the original images in the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/0*QPVvE0_tD-1UTWTu" /></figure><p>The best representation after 300 epochs. Almost no differences is cloud positioning and mountain shape. Even the lighting seems to match! Slight difference in height of mountain however.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/0*jXpkFLQfTQ3gD6lE" /></figure><p>The worst representation. Image has the same general shape but is extremely noisy.</p><p><strong>Ways to advance the model:</strong></p><p>As always there are always multiple methods to improve the model. In this case it is possible to use PixelCNN as a encoder. PixelCNN is an extremely powerful convolutional neural network and it is possible to use the feature extraction functionality of the CNN to make a meaningful representation of the data hence making it much easier for the decoder to remap the original image. It is also possible to use some form of manifold sampling in a low sample setting size as proposed here[9].</p><p><strong>Conclusion:</strong></p><p>In conclusion I propose a method to extend a dataset with relatively few images 4000 or more to an extremely large amount of data that can, in theory, be extended infinitely but that introduces the problem of dilution of the image leading to excessive loss of features but at least a minimum of two times the amount of data. I also proposed ways that the reader can utilize to effectively improve upon the given baseline of VQ-VAE. Check out the code to run your own experiments[10].</p><p><strong>Resources:</strong></p><p>[1] <a href="https://towardsdatascience.com/training-bert-at-a-university-eedcf940c754">Training BERT at a University — Towards Data Sciencehttps://towardsdatascience.com › training-bert-at-a-univ…</a></p><p>[2] <a href="https://towardsdatascience.com/training-bert-at-a-university-eedcf940c754">Training BERT at a University — Towards Data Sciencehttps://towardsdatascience.com › training-bert-at-a-univ…</a></p><p>[3] <a href="https://arxiv.org/pdf/2105.00026.pdf">https://arxiv.org/pdf/2105.00026.pdf</a></p><p>[4] <a href="https://arxiv.org/pdf/2012.00848.pdf">https://arxiv.org/pdf/2012.00848.pdf</a></p><p>[5] <a href="https://arxiv.org/pdf/1312.6114.pdf">https://arxiv.org/pdf/1312.6114.pdf</a></p><p>[6] <a href="https://arxiv.org/pdf/1711.00937.pdf">https://arxiv.org/pdf/1711.00937.pdf</a></p><p>[7] <a href="https://www.kaggle.com/datasets/paultimothymooney/chest-xray-pneumonia">https://www.kaggle.com/datasets/paultimothymooney/chest-xray-pneumonia</a></p><p>[8] <a href="https://www.kaggle.com/datasets/arnaud58/landscape-pictures">https://www.kaggle.com/datasets/arnaud58/landscape-pictures</a></p><p>[9] <a href="https://arxiv.org/pdf/2103.13751.pdf">https://arxiv.org/pdf/2103.13751.pdf</a></p><p>[10] <a href="https://github.com/arnavdantuluri/Vq-Vae-Image-Generation">https://github.com/arnavdantuluri/Vq-Vae-Image-Generation</a></p><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=339a8e12b779" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reinforcement Learning Snake Algorithm]]></title>
            <link>https://medium.com/@arnavdantuluri/reinforcement-learning-snake-algorithm-14a8d20dec7f?source=rss-d6494070acd5------2</link>
            <guid isPermaLink="false">https://medium.com/p/14a8d20dec7f</guid>
            <category><![CDATA[snake-games]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Arnav Dantuluri]]></dc:creator>
            <pubDate>Sun, 20 Feb 2022 17:24:44 GMT</pubDate>
            <atom:updated>2022-02-20T17:29:05.486Z</atom:updated>
            <content:encoded><![CDATA[<p>Training a snake algorithm is one of the most basic projects relating to reinforcement learning. It’s kinda like the “Hello World” of reinforcement learning. I recently discovered the youtube series by python engineer where he built a reinforcement learning algorithm from scratch using pytorch but I felt like he didn’t explain the concepts or the model very well. I am writing this article to explain the fundamentals of the algorithm and maybe some of the math behind it. Youtube video by the Python Engineer: <a href="https://youtu.be/PJl4iabBEz0">https://youtu.be/PJl4iabBEz0</a>. We start off with simply coding a snake game which can be made using pygame</p><pre>import pygame</pre><pre>import random</pre><pre>from enum import Enum</pre><pre>from collections import namedtuple</pre><pre>import time</pre><pre>pygame.init()</pre><pre>font = pygame.font.Font(&#39;arial.ttf&#39;, 25)</pre><pre>#font = pygame.font.SysFont(&#39;arial&#39;, 25)</pre><pre>class Direction(Enum):</pre><pre>RIGHT = 1</pre><pre>LEFT = 2</pre><pre>UP = 3</pre><pre>DOWN = 4</pre><pre>Point = namedtuple(&#39;Point&#39;, &#39;x, y&#39;)</pre><pre># rgb colors</pre><pre>WHITE = (255, 255, 255)</pre><pre>RED = (200,0,0)</pre><pre>BLUE1 = (0, 0, 255)</pre><pre>BLUE2 = (0, 100, 255)</pre><pre>BLACK = (0,0,0)</pre><pre>BLOCK_SIZE = 20</pre><pre>SPEED = 20</pre><pre>class Snake:</pre><pre>def __init__(self, w=640, h=480):</pre><pre>self.w = w</pre><pre>self.h = h</pre><pre># init display</pre><pre>self.display = pygame.display.set_mode((self.w, self.h))</pre><pre>pygame.display.set_caption(&#39;Snake&#39;)</pre><pre>self.clock = pygame.time.Clock()</pre><pre># init game state</pre><pre>self.direction = Direction.RIGHT</pre><pre>self.head = Point(self.w/2, self.h/2)</pre><pre>self.snake = [self.head,</pre><pre>Point(self.head.x-BLOCK_SIZE, self.head.y),</pre><pre>Point(self.head.x-(2*BLOCK_SIZE), self.head.y)]</pre><pre>self.score = 0</pre><pre>self.food = None</pre><pre>self._place_food()</pre><pre>def _place_food(self):</pre><pre>x = random.randint(0, (self.w-BLOCK_SIZE )//BLOCK_SIZE )*BLOCK_SIZE</pre><pre>y = random.randint(0, (self.h-BLOCK_SIZE )//BLOCK_SIZE )*BLOCK_SIZE</pre><pre>self.food = Point(x, y)</pre><pre>if self.food in self.snake:</pre><pre>self._place_food()</pre><pre>def play_step(self):</pre><pre># 1. collect user input</pre><pre>for event in pygame.event.get():</pre><pre>if event.type == pygame.QUIT:</pre><pre>pygame.quit()</pre><pre>quit()</pre><pre>if event.type == pygame.KEYDOWN:</pre><pre>if event.key == pygame.K_LEFT:</pre><pre>if self.direction == Direction.RIGHT:</pre><pre>self.direction = Direction.RIGHT</pre><pre>else:</pre><pre>self.direction = Direction.LEFT</pre><pre>time.sleep(0.03)</pre><pre>elif event.key == pygame.K_RIGHT:</pre><pre>if self.direction == Direction.LEFT:</pre><pre>self.direction = Direction.LEFT</pre><pre>else:</pre><pre>self.direction = Direction.RIGHT</pre><pre>time.sleep(0.03)</pre><pre>elif event.key == pygame.K_UP:</pre><pre>if self.direction == Direction.DOWN:</pre><pre>self.direction = Direction.DOWN</pre><pre>else:</pre><pre>self.direction = Direction.UP</pre><pre>time.sleep(0.03)</pre><pre>elif event.key == pygame.K_DOWN:</pre><pre>if self.direction == Direction.UP:</pre><pre>self.direction = Direction.UP</pre><pre>else:</pre><pre>self.direction = Direction.DOWN</pre><pre>time.sleep(0.03)</pre><pre># 2. move</pre><pre>self._move(self.direction) # update the head</pre><pre>self.snake.insert(0, self.head)</pre><pre># 3. check if game over</pre><pre>game_over = False</pre><pre>if self._is_collision():</pre><pre>game_over = True</pre><pre>return game_over, self.score</pre><pre># 4. place new food or just move</pre><pre>if self.head == self.food:</pre><pre>self.score += 1</pre><pre>self._place_food()</pre><pre>else:</pre><pre>self.snake.pop()</pre><pre># 5. update ui and clock</pre><pre>self._update_ui()</pre><pre>self.clock.tick(SPEED)</pre><pre># 6. return game over and score</pre><pre>return game_over, self.score</pre><pre>def _is_collision(self):</pre><pre># hits boundary</pre><pre>if self.head.x &gt; self.w - BLOCK_SIZE or self.head.x &lt; 0 or self.head.y &gt; self.h - BLOCK_SIZE or self.head.y &lt; 0:</pre><pre>return True</pre><pre># hits itself</pre><pre>if self.head in self.snake[1:]:</pre><pre>return True</pre><pre>return False</pre><pre>def _update_ui(self):</pre><pre>self.display.fill(BLACK)</pre><pre>for pt in self.snake:</pre><pre>pygame.draw.rect(self.display, BLUE1, pygame.Rect(pt.x, pt.y, BLOCK_SIZE, BLOCK_SIZE))</pre><pre>pygame.draw.rect(self.display, BLUE2, pygame.Rect(pt.x+4, pt.y+4, 12, 12))</pre><pre>pygame.draw.rect(self.display, RED, pygame.Rect(self.food.x, self.food.y, BLOCK_SIZE, BLOCK_SIZE))</pre><pre>text = font.render(&quot;Score: &quot; + str(self.score), True, WHITE)</pre><pre>self.display.blit(text, [0, 0])</pre><pre>pygame.display.flip()</pre><pre>def _move(self, direction):</pre><pre>x = self.head.x</pre><pre>y = self.head.y</pre><pre>if direction == Direction.RIGHT:</pre><pre>x += BLOCK_SIZE</pre><pre>elif direction == Direction.LEFT:</pre><pre>x -= BLOCK_SIZE</pre><pre>elif direction == Direction.DOWN:</pre><pre>y += BLOCK_SIZE</pre><pre>elif direction == Direction.UP:</pre><pre>y -= BLOCK_SIZE</pre><pre>self.head = Point(x, y)</pre><pre>if __name__ == &#39;__main__&#39;:</pre><pre>game = Snake()</pre><pre># game loop</pre><pre>while True:</pre><pre>game_over, score = game.play_step()</pre><pre>if game_over == True:</pre><pre>break</pre><pre>print(&#39;Final Score&#39;, score)</pre><pre>pygame.quit()</pre><p>This is the code for the game. Let’s walk through it</p><pre>class Direction(Enum):</pre><pre>RIGHT = 1</pre><pre>LEFT = 2</pre><pre>UP = 3</pre><pre>DOWN = 4</pre><p>We first instantiate a Direction class to simplify the process of changing the direction of the snake with the four basic directions. The rest of the game is pretty self explanatory with a collision detection system.</p><pre>def _is_collision(self):</pre><pre># hits boundary</pre><pre>if self.head.x &gt; self.w - BLOCK_SIZE or self.head.x &lt; 0 or self.head.y &gt; self.h - BLOCK_SIZE or self.head.y &lt; 0:</pre><pre>return True</pre><pre># hits itself</pre><pre>if self.head in self.snake[1:]:</pre><pre>return True</pre><pre>return False</pre><p>To check if the snake exits the map or to see if the head of the snake hits itself in a point that is not the head. It also implements a very simple system for moving</p><pre>def _move(self, direction):</pre><pre>x = self.head.x</pre><pre>y = self.head.y</pre><pre>if direction == Direction.RIGHT:</pre><pre>x += BLOCK_SIZE</pre><pre>elif direction == Direction.LEFT:</pre><pre>x -= BLOCK_SIZE</pre><pre>elif direction == Direction.DOWN:</pre><pre>y += BLOCK_SIZE</pre><pre>elif direction == Direction.UP:</pre><pre>y -= BLOCK_SIZE</pre><pre>self.head = Point(x, y)</pre><p>which simply updates the head and body of the snake and shifts the body left, right, up, or down based on the current direction of the snake. The changing of direction is facilitated by a simple key system implemented through pygames in-built input system</p><pre>for event in pygame.event.get():</pre><pre>if event.type == pygame.QUIT:</pre><pre>pygame.quit()</pre><pre>quit()</pre><pre>if event.type == pygame.KEYDOWN:</pre><pre>if event.key == pygame.K_LEFT:</pre><pre>if self.direction == Direction.RIGHT:</pre><pre>self.direction = Direction.RIGHT</pre><pre>else:</pre><pre>self.direction = Direction.LEFT</pre><pre>time.sleep(0.03)</pre><pre>elif event.key == pygame.K_RIGHT:</pre><pre>if self.direction == Direction.LEFT:</pre><pre>self.direction = Direction.LEFT</pre><pre>else:</pre><pre>self.direction = Direction.RIGHT</pre><pre>time.sleep(0.03)</pre><pre>elif event.key == pygame.K_UP:</pre><pre>if self.direction == Direction.DOWN:</pre><pre>self.direction = Direction.DOWN</pre><pre>else:</pre><pre>self.direction = Direction.UP</pre><pre>time.sleep(0.03)</pre><pre>elif event.key == pygame.K_DOWN:</pre><pre>if self.direction == Direction.UP:</pre><pre>self.direction = Direction.UP</pre><pre>else:</pre><pre>self.direction = Direction.DOWN</pre><pre>time.sleep(0.03)</pre><p>We also add a caviet which prevents us from going in the opposite direction we are traveling in which PE didn’t implement. We also add a time.sleep() for 0.03 seconds to prevent quick presses from accidentally killing the player which PE didn’t implement either. That covers the basis of the game. Now we move on to the environment.</p><pre>import pygame</pre><pre>import random</pre><pre>from enum import Enum</pre><pre>from collections import namedtuple</pre><pre>import numpy as np</pre><pre>pygame.init()</pre><pre>font = pygame.font.Font(&#39;arial.ttf&#39;, 25)</pre><pre>#font = pygame.font.SysFont(&#39;arial&#39;, 25)</pre><pre>class Direction(Enum):</pre><pre>RIGHT = 1</pre><pre>LEFT = 2</pre><pre>UP = 3</pre><pre>DOWN = 4</pre><pre>Point = namedtuple(&#39;Point&#39;, &#39;x, y&#39;)</pre><pre># rgb colors</pre><pre>WHITE = (255, 255, 255)</pre><pre>RED = (200,0,0)</pre><pre>BLUE1 = (0, 0, 255)</pre><pre>BLUE2 = (0, 100, 255)</pre><pre>BLACK = (0,0,0)</pre><pre>BLOCK_SIZE = 20</pre><pre>SPEED = 100</pre><pre>class SnakeGameAI:</pre><pre>def __init__(self, w=640, h=480):</pre><pre>self.w = w</pre><pre>self.h = h</pre><pre># init display</pre><pre>self.display = pygame.display.set_mode((self.w, self.h))</pre><pre>pygame.display.set_caption(&#39;Snake&#39;)</pre><pre>self.clock = pygame.time.Clock()</pre><pre>self.reset()</pre><pre>def reset(self):</pre><pre># init game state</pre><pre>self.direction = Direction.RIGHT</pre><pre>self.head = Point(self.w/2, self.h/2)</pre><pre>self.snake = [self.head,</pre><pre>Point(self.head.x-BLOCK_SIZE, self.head.y),</pre><pre>Point(self.head.x-(2*BLOCK_SIZE), self.head.y)]</pre><pre>self.score = 0</pre><pre>self.food = None</pre><pre>self._place_food()</pre><pre>self.frame_iteration = 0</pre><pre>def _place_food(self):</pre><pre>x = random.randint(0, (self.w-BLOCK_SIZE )//BLOCK_SIZE )*BLOCK_SIZE</pre><pre>y = random.randint(0, (self.h-BLOCK_SIZE )//BLOCK_SIZE )*BLOCK_SIZE</pre><pre>self.food = Point(x, y)</pre><pre>if self.food in self.snake:</pre><pre>self._place_food()</pre><pre>def play_step(self, action):</pre><pre>self.frame_iteration += 1</pre><pre># 1. collect user input</pre><pre>for event in pygame.event.get():</pre><pre>if event.type == pygame.QUIT:</pre><pre>pygame.quit()</pre><pre>quit()</pre><pre># 2. move</pre><pre>self._move(action) # update the head</pre><pre>self.snake.insert(0, self.head)</pre><pre># 3. check if game over</pre><pre>reward = 0</pre><pre>game_over = False</pre><pre>if self.is_collision() or self.frame_iteration &gt; 100*len(self.snake):</pre><pre>game_over = True</pre><pre>reward = -10</pre><pre>return reward, game_over, self.score</pre><pre># 4. place new food or just move</pre><pre>if self.head == self.food:</pre><pre>self.score += 1</pre><pre>reward = 10</pre><pre>self._place_food()</pre><pre>else:</pre><pre>self.snake.pop()</pre><pre># 5. update ui and clock</pre><pre>self._update_ui()</pre><pre>self.clock.tick(SPEED)</pre><pre># 6. return game over and score</pre><pre>return reward, game_over, self.score</pre><pre>def is_collision(self, pt=None):</pre><pre>if pt is None:</pre><pre>pt = self.head</pre><pre># hits boundary</pre><pre>if pt.x &gt; self.w - BLOCK_SIZE or pt.x &lt; 0 or pt.y &gt; self.h - BLOCK_SIZE or pt.y &lt; 0:</pre><pre>return True</pre><pre># hits itself</pre><pre>if pt in self.snake[1:]:</pre><pre>return True</pre><pre>return False</pre><pre>def _update_ui(self):</pre><pre>self.display.fill(BLACK)</pre><pre>for pt in self.snake:</pre><pre>pygame.draw.rect(self.display, BLUE1, pygame.Rect(pt.x, pt.y, BLOCK_SIZE, BLOCK_SIZE))</pre><pre>pygame.draw.rect(self.display, BLUE2, pygame.Rect(pt.x+4, pt.y+4, 12, 12))</pre><pre>pygame.draw.rect(self.display, RED, pygame.Rect(self.food.x, self.food.y, BLOCK_SIZE, BLOCK_SIZE))</pre><pre>text = font.render(&quot;Score: &quot; + str(self.score), True, WHITE)</pre><pre>self.display.blit(text, [0, 0])</pre><pre>pygame.display.flip()</pre><pre>def _move(self, action):</pre><pre># [straight, right, left]</pre><pre>clock_wise = [Direction.RIGHT, Direction.DOWN, Direction.LEFT, Direction.UP]</pre><pre>idx = clock_wise.index(self.direction)</pre><pre>if np.array_equal(action, [1, 0, 0]):</pre><pre>new_dir = clock_wise[idx] # no change</pre><pre>elif np.array_equal(action, [0, 1, 0]):</pre><pre>next_idx = (idx + 1) % 4</pre><pre>new_dir = clock_wise[next_idx] # right turn r -&gt; d -&gt; l -&gt; u</pre><pre>else: # [0, 0, 1]</pre><pre>next_idx = (idx - 1) % 4</pre><pre>new_dir = clock_wise[next_idx] # left turn r -&gt; u -&gt; l -&gt; d</pre><pre>self.direction = new_dir</pre><pre>x = self.head.x</pre><pre>y = self.head.y</pre><pre>if self.direction == Direction.RIGHT:</pre><pre>x += BLOCK_SIZE</pre><pre>elif self.direction == Direction.LEFT:</pre><pre>x -= BLOCK_SIZE</pre><pre>elif self.direction == Direction.DOWN:</pre><pre>y += BLOCK_SIZE</pre><pre>elif self.direction == Direction.UP:</pre><pre>y -= BLOCK_SIZE</pre><pre>self.head = Point(x, y)</pre><p>The env is extremely similar to the game with a few extra functions that enable the algorithm to learn including the play_step function, the reset function, and the _move function. The play_step function handles all the updates that occur after the move function that takes in a 1d array that is either [1, 0, 0], [0, 1, 0], or [0, 0, 1] which controls if the agent moves clockwise, anti-clockwise or performs no action. These actions are performed in the _move function. Next we move on to the agent</p><pre>import torch</pre><pre>import random</pre><pre>import numpy as np</pre><pre>from collections import deque</pre><pre>from env import SnakeGameAI, Direction, Point</pre><pre>from model import Linear_QNet, QTrainer</pre><pre>MAX_MEMORY = 100_000</pre><pre>BATCH_SIZE = 1000</pre><pre>LR = 0.001</pre><pre>class Agent:</pre><pre>def __init__(self):</pre><pre>self.n_games = 0</pre><pre>self.epsilon = 0 # randomness</pre><pre>self.gamma = 0.9 # discount rate</pre><pre>self.memory = deque(maxlen=MAX_MEMORY) # popleft()</pre><pre>self.model = Linear_QNet(11, 256, 3)#.to(device=torch.device(&#39;cuda:0&#39;))</pre><pre>self.trainer = QTrainer(self.model, lr=LR, gamma=self.gamma)#.to(device=torch.device(&#39;cuda:0&#39;))</pre><pre>def get_state(self, game):</pre><pre>head = game.snake[0]</pre><pre>point_l = Point(head.x - 20, head.y)</pre><pre>point_r = Point(head.x + 20, head.y)</pre><pre>point_u = Point(head.x, head.y - 20)</pre><pre>point_d = Point(head.x, head.y + 20)</pre><pre>dir_l = game.direction == Direction.LEFT</pre><pre>dir_r = game.direction == Direction.RIGHT</pre><pre>dir_u = game.direction == Direction.UP</pre><pre>dir_d = game.direction == Direction.DOWN</pre><pre>state = [</pre><pre># Danger straight</pre><pre>(dir_r and game.is_collision(point_r)) or</pre><pre>(dir_l and game.is_collision(point_l)) or</pre><pre>(dir_u and game.is_collision(point_u)) or</pre><pre>(dir_d and game.is_collision(point_d)),</pre><pre># Danger right</pre><pre>(dir_u and game.is_collision(point_r)) or</pre><pre>(dir_d and game.is_collision(point_l)) or</pre><pre>(dir_l and game.is_collision(point_u)) or</pre><pre>(dir_r and game.is_collision(point_d)),</pre><pre># Danger left</pre><pre>(dir_d and game.is_collision(point_r)) or</pre><pre>(dir_u and game.is_collision(point_l)) or</pre><pre>(dir_r and game.is_collision(point_u)) or</pre><pre>(dir_l and game.is_collision(point_d)),</pre><pre># Move direction</pre><pre>dir_l,</pre><pre>dir_r,</pre><pre>dir_u,</pre><pre>dir_d,</pre><pre># Food location</pre><pre>game.food.x &lt; game.head.x, # food left</pre><pre>game.food.x &gt; game.head.x, # food right</pre><pre>game.food.y &lt; game.head.y, # food up</pre><pre>game.food.y &gt; game.head.y # food down</pre><pre>]</pre><pre>return np.array(state, dtype=int)</pre><pre>def remember(self, state, action, reward, next_state, done):</pre><pre>self.memory.append((state, action, reward, next_state, done)) # popleft if MAX_MEMORY is reached</pre><pre>def train_long_memory(self):</pre><pre>if len(self.memory) &gt; BATCH_SIZE:</pre><pre>mini_sample = random.sample(self.memory, BATCH_SIZE) # list of tuples</pre><pre>else:</pre><pre>mini_sample = self.memory</pre><pre>states, actions, rewards, next_states, dones = zip(*mini_sample)</pre><pre>self.trainer.train_step(states, actions, rewards, next_states, dones)</pre><pre>#for state, action, reward, nexrt_state, done in mini_sample:</pre><pre># self.trainer.train_step(state, action, reward, next_state, done)</pre><pre>def train_short_memory(self, state, action, reward, next_state, done):</pre><pre>self.trainer.train_step(state, action, reward, next_state, done)</pre><pre>def get_action(self, state):</pre><pre># random moves: tradeoff exploration / exploitation</pre><pre>self.epsilon = 80 - self.n_games</pre><pre>final_move = [0,0,0]</pre><pre>if random.randint(0, 200) &lt; self.epsilon:</pre><pre>move = random.randint(0, 2)</pre><pre>final_move[move] = 1</pre><pre>else:</pre><pre>state0 = torch.tensor(state, dtype=torch.float)</pre><pre>prediction = self.model(state0)</pre><pre>move = torch.argmax(prediction).item()</pre><pre>final_move[move] = 1</pre><pre>return final_move</pre><pre>def train():</pre><pre>record = 0</pre><pre>agent = Agent()</pre><pre>game = SnakeGameAI()</pre><pre>while True:</pre><pre># get old state</pre><pre>state_old = agent.get_state(game)</pre><pre># get move</pre><pre>final_move = agent.get_action(state_old)</pre><pre># perform move and get new state</pre><pre>reward, done, score = game.play_step(final_move)</pre><pre>state_new = agent.get_state(game)</pre><pre># train short memory</pre><pre>agent.train_short_memory(state_old, final_move, reward, state_new, done)</pre><pre># remember</pre><pre>agent.remember(state_old, final_move, reward, state_new, done)</pre><pre>if done:</pre><pre># train long memory, plot result</pre><pre>game.reset()</pre><pre>agent.n_games += 1</pre><pre>agent.train_long_memory()</pre><pre>if score &gt; record:</pre><pre>record = score</pre><pre>agent.model.save()</pre><pre>print(&#39;Game&#39;, agent.n_games, &#39;Score&#39;, score, &#39;Record:&#39;, record)</pre><pre>if __name__ == &#39;__main__&#39;:</pre><pre>train()</pre><p>For the enviornment please refer to PE’s video because he explained in a beautiful way that I cannot replicate in text. We can next move on to the model which is the part where I found PE’s explanation to be lacking. The code behind this is</p><pre>import torch</pre><pre>import torch.nn as nn</pre><pre>import torch.optim as optim</pre><pre>import torch.nn.functional as F</pre><pre>import os</pre><pre>class Linear_QNet(nn.Module):</pre><pre>def __init__(self, input_size, hidden_size, output_size):</pre><pre>super().__init__()</pre><pre>self.linear1 = nn.Linear(input_size, hidden_size)</pre><pre>self.linear2 = nn.Linear(hidden_size, output_size)</pre><pre>def forward(self, x):</pre><pre>x = F.relu(self.linear1(x))</pre><pre>x = self.linear2(x)</pre><pre>return x</pre><pre>def save(self, file_name=&#39;model.pth&#39;):</pre><pre>model_folder_path = &#39;./model&#39;</pre><pre>if not os.path.exists(model_folder_path):</pre><pre>os.makedirs(model_folder_path)</pre><pre>file_name = os.path.join(model_folder_path, file_name)</pre><pre>torch.save(self.state_dict(), file_name)</pre><pre>class QTrainer:</pre><pre>def __init__(self, model, lr, gamma):</pre><pre>self.lr = lr</pre><pre>self.gamma = gamma</pre><pre>self.model = model</pre><pre>self.optimizer = optim.Adam(model.parameters(), lr=self.lr)</pre><pre>self.criterion = nn.MSELoss()</pre><pre>def train_step(self, state, action, reward, next_state, done):</pre><pre>state = torch.tensor(state, dtype=torch.float)</pre><pre>next_state = torch.tensor(next_state, dtype=torch.float)</pre><pre>action = torch.tensor(action, dtype=torch.long)</pre><pre>reward = torch.tensor(reward, dtype=torch.float)</pre><pre># (n, x)</pre><pre>if len(state.shape) == 1:</pre><pre># (1, x)</pre><pre>state = torch.unsqueeze(state, 0)</pre><pre>next_state = torch.unsqueeze(next_state, 0)</pre><pre>action = torch.unsqueeze(action, 0)</pre><pre>reward = torch.unsqueeze(reward, 0)</pre><pre>done = (done, )</pre><pre># 1: predicted Q values with current state</pre><pre>pred = self.model(state)</pre><pre>target = pred.clone()</pre><pre>for idx in range(len(done)):</pre><pre>Q_new = reward[idx]</pre><pre>if not done[idx]:</pre><pre>Q_new = reward[idx] + self.gamma * torch.max(self.model(next_state[idx]))</pre><pre>target[idx][torch.argmax(action[idx]).item()] = Q_new</pre><pre># 2: Q_new = r + y * max(next_predicted Q value) -&gt; only do this if not done</pre><pre># pred.clone()</pre><pre># preds[argmax(action)] = Q_new</pre><pre>self.optimizer.zero_grad()</pre><pre>loss = self.criterion(target, pred)</pre><pre>loss.backward()</pre><pre>self.optimizer.step()</pre><p>The model is a very lightweight Linear model implemented in pytorch an extremely versatile library for machine learning. I chose pytorch over my normal choice of tensorflow because of simple it was to implement a pytorch model as compared to a pytorch model. The model takes in 11 values as input has 256 nodes as a hidden layer and outputs a value from 0 to 2 as an output. We convert each parameter to a tensor using these lines of code</p><pre>state = torch.tensor(state, dtype=torch.float)</pre><pre>next_state = torch.tensor(next_state, dtype=torch.float)</pre><pre>action = torch.tensor(action, dtype=torch.long)</pre><pre>reward = torch.tensor(reward, dtype=torch.float)</pre><p>and each of these parameters are then unsqueezed to make them compatible with the input layers of the neural network and the done parameter is converted to a tuple with one element</p><pre>state = torch.unsqueeze(state, 0)</pre><pre>next_state = torch.unsqueeze(next_state, 0)</pre><pre>action = torch.unsqueeze(action, 0)</pre><pre>reward = torch.unsqueeze(reward, 0)</pre><pre>done = (done, )</pre><p>After all that is done we calculate the predicted outcome and the outcome the model provided and using those calculate the loss.</p><pre>Q_new = reward[idx]</pre><pre>if not done[idx]:</pre><pre>Q_new = reward[idx] + self.gamma * torch.max(self.model(next_state[idx]))</pre><pre>target[idx][torch.argmax(action[idx]).item()] = Q_new</pre><pre># 2: Q_new = r + y * max(next_predicted Q value)</pre><p>After that we simply optimize the model and its parameters</p><pre>self.optimizer.zero_grad()</pre><pre>loss = self.criterion(target, pred)</pre><pre>loss.backward()</pre><pre>self.optimizer.step()</pre><p>This model and training method produce results such as: <a href="https://youtu.be/kxFVMeoqzkM">https://youtu.be/kxFVMeoqzkM</a> which was accomplished after 30 minutes of training.</p><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb"><strong>Become a Writer</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14a8d20dec7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generating Realistic Human Faces]]></title>
            <link>https://medium.com/@arnavdantuluri/generating-realistic-human-faces-3e5fa40c76b3?source=rss-d6494070acd5------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e5fa40c76b3</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[math]]></category>
            <dc:creator><![CDATA[Arnav Dantuluri]]></dc:creator>
            <pubDate>Wed, 02 Feb 2022 15:14:39 GMT</pubDate>
            <atom:updated>2022-02-11T13:45:37.764Z</atom:updated>
            <content:encoded><![CDATA[<p>Machine learning is probably one of the most versatile fields today but at the same time it is probably one of the most volatile. New discoveries in any field can shake the foundation and lead to new research in that area. For example the introduction of the ConvNet for computer vision. The ConvNet was built to extract features from images but it has now also been used to process sequential data a task that was previously well suited for LSTM’s and RNN’s. At the moment the most promising field of machine learning includes unsupervised learning and more specifically generative models like, GANs (Generative Adversarial networks) and Transformer neural networks. Today I am going to tackle the problem of generating faces using Generative Adversarial Neural Networks.</p><h3>A Bit of Background about GANs:</h3><p>The generative adversarial neural network was a theory proposed by Ian Goodfellow in back in 2014 and has since found many applications in the fields of machine learning. It can be used to generate images from a dataset of images which is it’s main purpose however generative models can also be used in reinforcement learning (For more information: <a href="https://simons.berkeley.edu/talks/tbd-241">https://simons.berkeley.edu/talks/tbd-241</a>). Generative models work by pitting two models against each other. This makes the model extremely good for unsupervised learning but also makes it extremely volatile and hard for the model to converge without a lot of data. The model works by having a generator and a discriminator. The discriminator’s job is to differentiate between the images generated by the generator and the dataset. The generator’s job is to generate images from a latent space that is provided as input to the generator. It tries to generate images that are similar enough to the dataset to fool the discriminator.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F6v7lJHFaZZ4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D6v7lJHFaZZ4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F6v7lJHFaZZ4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1400d8d056541d17938037c4ced19cee/href">https://medium.com/media/1400d8d056541d17938037c4ced19cee/href</a></iframe><p>Credit to Joseph Rocca for the amazing explanation.</p><h3>The math behind Generative model:</h3><p>We previously explored the fundamentals of General Adversarial Networks at a high level, let us now delve into the math and fundamentals of a generative model by analyzing the math presented by Ian Goodfellow in his paper Generative Adversarial Nets (<a href="https://arxiv.org/pdf/1406.2661.pdf">https://arxiv.org/pdf/1406.2661.pdf</a>). In his paper he proposes this math equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xGD4I7fwNC5LVIGGnFSsrw.png" /><figcaption>Math equation for GANs from Ian Goodfellow’s paper</figcaption></figure><p>The function D(x) refers to the discriminator taking in real images and outputting a value which is then scaled by the log function to return a value between 0 and 1 the same occurs in the log(1-D(G(z))) which takes in the output of the generator model and return the scaled value subtracted from one returning a value on the lower end of the scale from 0 to 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iv9PfCEZl6itXsfoM75GfA.png" /><figcaption>Math equation for Discriminator gradient from Ian Goodfellow’s paper</figcaption></figure><p>Input’s the x values of the real images and G(z) values of the fake images generated by the discriminator which is again scaled by the log function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*R_3dDCQldLLidiGxIFzy1Q.png" /><figcaption>Math Equation for generator gradient</figcaption></figure><p>The generator is inputted a random noise vector (z) the output of which is then passed into the discriminator function which scales the value using the log function.</p><p>The model is trained in batches with the discriminator being trained first for an n number of steps after which the training stops and the generative model begins to train trying to generate images from a gaussian noise trying to fool the discriminator with an image that it thinks is the same as the ones in the database.</p><h3>Implementation of a GAN:</h3><p>Implementation of a GAN is very straight forward if you use a high level api like Tensorflow it is still hefty in length however.</p><pre>discriminator = keras.Sequential(</pre><pre>[</pre><pre>keras.Input(shape=(128, 128, 3)),</pre><pre>keras.layers.Conv2D(filters=64, kernel_size=4, strides=2, padding=&#39;same&#39;),</pre><pre>keras.layers.LeakyReLU(alpha=0.2),</pre><pre>keras.layers.Conv2D(filters=128, kernel_size=4, strides=2, padding=&#39;same&#39;),</pre><pre>keras.layers.LeakyReLU(alpha=0.2),</pre><pre>keras.layers.Conv2D(filters=128, kernel_size=4, strides=2, padding=&#39;same&#39;),</pre><pre>keras.layers.LeakyReLU(alpha=0.2),</pre><pre>keras.layers.Flatten(),</pre><pre>keras.layers.Dropout(0.2),</pre><pre>keras.layers.Dense(units=1, activation=&#39;sigmoid&#39;)</pre><pre>],</pre><pre>name=&#39;discriminator&#39;</pre><pre>)</pre><pre>discriminator.summary()</pre><p>The discriminator follows a similar model as that of a deep convolutional neural network which allows it to have a better accuracy when discriminating against generated images and images from the dataset.</p><pre>latent_dim = 128</pre><pre>generator = keras.Sequential([</pre><pre>keras.Input(shape=latent_dim),</pre><pre>keras.layers.Dense(16*16*128),</pre><pre>keras.layers.Reshape((16, 16, 128)),</pre><pre>layers.Conv2DTranspose(128, kernel_size=4, strides=2, padding=&quot;same&quot;),</pre><pre>layers.LeakyReLU(alpha=0.2),</pre><pre>layers.Conv2DTranspose(256, kernel_size=4, strides=2, padding=&quot;same&quot;),</pre><pre>layers.LeakyReLU(alpha=0.2),</pre><pre>layers.Conv2DTranspose(512, kernel_size=4, strides=2, padding=&quot;same&quot;),</pre><pre>layers.LeakyReLU(alpha=0.2),</pre><pre>keras.layers.Conv2D(3, kernel_size=4, padding=&#39;same&#39;, activation=&#39;sigmoid&#39;)</pre><pre>],</pre><pre>name=&#39;generator&#39;</pre><pre>)</pre><pre>generator.summary()</pre><p>The generator follows the model similar to that of a fully connected neural network with conv2d transpose layers returning a tensor with double the size as the input tensor.</p><pre>class GAN(keras.Model):</pre><pre>def __init__(self, discriminator, generator, latent_dim):</pre><pre>super(GAN, self).__init__()</pre><pre>self.discriminator = discriminator</pre><pre>self.generator = generator</pre><pre>self.latent_dim = latent_dim</pre><pre>def compile(self, d_optimizer, g_optimizer, loss_fn):</pre><pre>super(GAN, self).compile()</pre><pre>self.d_optimizer = d_optimizer</pre><pre>self.g_optimizer = g_optimizer</pre><pre>self.loss_fn = loss_fn</pre><pre>self.d_loss_metric = keras.metrics.Mean(name=&quot;d_loss&quot;)</pre><pre>self.g_loss_metric = keras.metrics.Mean(name=&quot;g_loss&quot;)</pre><pre>@property</pre><pre>def metrics(self):</pre><pre>return [self.d_loss_metric, self.g_loss_metric]</pre><pre>def train_step(self, real_images):</pre><pre># Sample random points in the latent space</pre><pre>batch_size = tf.shape(real_images)[0]</pre><pre>random_latent_vectors = tf.random.normal(shape=(batch_size, self.latent_dim))</pre><pre># Decode them to fake images</pre><pre>generated_images = self.generator(random_latent_vectors)</pre><pre># Combine them with real images</pre><pre>combined_images = tf.concat([generated_images, real_images], axis=0)</pre><pre># Assemble labels discriminating real from fake images</pre><pre>labels = tf.concat(</pre><pre>[tf.ones((batch_size, 1)), tf.zeros((batch_size, 1))], axis=0</pre><pre>)</pre><pre># Add random noise to the labels - important trick!</pre><pre>labels += 0.05 * tf.random.uniform(tf.shape(labels))</pre><pre># Train the discriminator</pre><pre>with tf.GradientTape() as tape:</pre><pre>predictions = self.discriminator(combined_images)</pre><pre>d_loss = self.loss_fn(labels, predictions)</pre><pre>grads = tape.gradient(d_loss, self.discriminator.trainable_weights)</pre><pre>self.d_optimizer.apply_gradients(</pre><pre>zip(grads, self.discriminator.trainable_weights)</pre><pre>)</pre><pre># Sample random points in the latent space</pre><pre>random_latent_vectors = tf.random.normal(shape=(batch_size, self.latent_dim))</pre><pre># Assemble labels that say &quot;all real images&quot;</pre><pre>misleading_labels = tf.zeros((batch_size, 1))</pre><pre># Train the generator (note that we should *not* update the weights</pre><pre># of the discriminator)!</pre><pre>with tf.GradientTape() as tape:</pre><pre>predictions = self.discriminator(self.generator(random_latent_vectors))</pre><pre>g_loss = self.loss_fn(misleading_labels, predictions)</pre><pre>grads = tape.gradient(g_loss, self.generator.trainable_weights)</pre><pre>self.g_optimizer.apply_gradients(zip(grads, self.generator.trainable_weights))</pre><pre># Update metrics</pre><pre>self.d_loss_metric.update_state(d_loss)</pre><pre>self.g_loss_metric.update_state(g_loss)</pre><pre>return {</pre><pre>&quot;d_loss&quot;: self.d_loss_metric.result(),</pre><pre>&quot;g_loss&quot;: self.g_loss_metric.result(),</pre><pre>}</pre><p>Code adapted from keras DCGAN model</p><p>We can create a class called GAN which contains all the methods we need to train a generative model. In the compile function we simply instantiate the parameters. The real complex behavior is in the train_step function. This function includes two phases.</p><ul><li>In phase one we feed a Gaussian Noise to the generator to generate fake images, and we complete this batch by concatenating an equal number of real images. The targets are set to 0 for fake images and 1 for real images(these labels are used to compute the loss function). We then train the discriminator on this batch.</li><li>In phase two we feed the GAN some gaussian noise. The generator then starts to generate fake images while the discriminator tries to guess whether the images are real of fake. We also create “misleading labels” to make the discriminator believe the fake images are real</li></ul><p>Running this code produces pretty close images with slight imperfections caused because the generator didn&#39;t fully converge.</p><p>Check out the tutorial by tensorflow on mnist to implement the GAN yourself: <a href="https://www.tensorflow.org/tutorials/generative/dcgan">https://www.tensorflow.org/tutorials/generative/dcgan</a></p><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Become a ML writer</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e5fa40c76b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OpenAi Request For Research XOR Problem]]></title>
            <link>https://medium.com/@arnavdantuluri/openai-request-for-research-67d8dc58e75a?source=rss-d6494070acd5------2</link>
            <guid isPermaLink="false">https://medium.com/p/67d8dc58e75a</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[research]]></category>
            <category><![CDATA[lstm]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Arnav Dantuluri]]></dc:creator>
            <pubDate>Sun, 26 Dec 2021 22:05:40 GMT</pubDate>
            <atom:updated>2021-12-28T17:06:07.815Z</atom:updated>
            <content:encoded><![CDATA[<p>OpenAi released a couple of research problems that they wanted solved and as an avid learner of Machine Learning I decided to tackle their warmup problem. You can view the rest of their requests here <a href="https://openai.com/blog/requests-for-research-2/">https://openai.com/blog/requests-for-research-2/</a></p><p>The problem is to Train an LSTM to solve the XOR problem: that is, given a sequence of bits, determine its parity. The <a href="http://colah.github.io/posts/2015-08-Understanding-LSTMs/">LSTM</a> should consume the sequence, one bit at a time, and then output the correct answer at the sequence’s end. Test the two approaches below:</p><ul><li>Generate a dataset of random 100,000 binary strings of length 50. Train the LSTM; what performance do you get?</li><li>Generate a dataset of random 100,000 binary strings, where the length of each string is independently and randomly chosen between 1 and 50. Train the LSTM. Does it succeed? What explains the difference?</li></ul><p>The XOR Problem:</p><p>What it the XOR problem? In simple terms it is a binary classification problem where the input data consists of a vector of binary numbers and the target consists of a 0 or a 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JnwlESZow5mQ1FmKrITwDw.png" /><figcaption>Image adapted from <a href="http://www.cs.stir.ac.uk/courses/ITNP4B/lectures/kms/2-Perceptrons.pdf">Kevin Swingler</a>.</figcaption></figure><h3><strong>Problem 1:</strong></h3><pre>import numpy as np</pre><pre>def gen_len50(size=100000):</pre><pre>X_data_1 = []</pre><pre>Y_data_1 = []</pre><pre>for i in range(size):</pre><pre>length = random.randint(1, 50)</pre><pre>data = np.random.randint(2, size=(1, length)).astype(&quot;float32&quot;)</pre><pre>data = pad_sequences(data, maxlen=50, dtype=&#39;float32&#39;,       padding=&#39;pre&#39;)</pre><pre>X_data_1.append(data)</pre><pre>labels = [0 if np.sum(X_data_1[i])%2 == 0 else 1]</pre><pre>Y_data_1.append(labels)</pre><pre>return X_data_1, Y_data_1</pre><p>To generate the dataset we import numpy as iterate through the for loop 100000 times to generate a list of length 100000 each consisting of a binary string of a constant length of 50. Each data element has a corresponding label which is either 0 or 1.</p><p>We then define a very simple LSTM network using Keras, a very popular and simple to use Machine Learning Library.</p><pre>model = Sequential([</pre><pre>LSTM(32, return_sequences=True, activation=&#39;sigmoid&#39;, input_shape=(1, 50)),</pre><pre>LSTM(64, return_sequences=True, activation=&#39;sigmoid&#39;),</pre><pre>Dense(1, activation=&#39;sigmoid&#39;)</pre><pre>])</pre><p>We split the Dataset into training and testing datasets to evaluate the model after training using a split size of 20%</p><pre>split_size = 100000 * 0.20</pre><pre>X_train = X_data1[split_size:]</pre><pre>X_test = X_data1[:split_size]</pre><pre>Y_train = Y_data1[split_size:]</pre><pre>Y_test = Y_data1[:split_size]</pre><p>We compile the model using Adam as an optimizer, Binary Cross entropy as a loss due to the problem being a binary classification problem and keeping track of the accuracy.</p><pre>model.compile(&#39;adam&#39;, loss=&#39;binary_crossentropy&#39;, metrics=[&#39;acc&#39;])</pre><p>We convert the list into numpy arrays and normalize the data to optimize training.</p><pre>X_train = np.asarray(X_train)</pre><pre>norm = np.linalg.norm(X_train)<br>normal_array = X_train/norm<br>print(normal_array)</pre><p>We do this for all the training and testing lists</p><pre>history = model.fit(X_train, Y_train, epochs=50, batch_size=32, shuffle=True)</pre><p>We then train the model on the normalized X and y values for 50 epochs. Not nearly enough to optimize an LSTM model ,which are infamous for taking an extremely long time to train, but enough to draw conclusions between problem 1 and 2.</p><pre>def plot_model(history):</pre><pre>&#39;&#39;&#39; Plot model accuracy and loss</pre><pre>Args:</pre><pre>history: Keras dictionary contatining training/validation loss/acc</pre><pre>Returns:</pre><pre>Plots model&#39;s training/validation loss and accuracy history</pre><pre>&#39;&#39;&#39;</pre><pre>loss = history.history[&#39;loss&#39;]</pre><pre>epochs = range(1, len(loss) + 1)<br></pre><pre>plt.figure()</pre><pre>plt.plot(epochs, loss, &#39;b&#39;, label=&#39;Training loss&#39;)</pre><pre>plt.title(&#39;Training  loss&#39;)</pre><pre>plt.xlabel(&#39;Epochs&#39;)</pre><pre>plt.ylabel(&#39;Loss&#39;)</pre><pre>plt.legend()</pre><pre>plt.figure()</pre><pre>acc = history.history[&#39;acc&#39;]</pre><pre>plt.plot(epochs, acc, &#39;bo&#39;, label=&#39;Training acc&#39;)</pre><pre>plt.title(&#39;Training accuracy&#39;)</pre><pre>plt.xlabel(&#39;Epochs&#39;)</pre><pre>plt.ylabel(&#39;Loss&#39;)</pre><pre>plt.legend()</pre><pre>plt.show()</pre><pre>return</pre><p>We can then plot the accuracy and loss and draw conclusions from that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*oHnyGXydrgdbuboUvOYJBg.png" /><figcaption>Author’s Image of Loss and Accuracy for 1st model</figcaption></figure><p>The accuracy shows a constant upward trend but a slow curve to the end leading to a stagnating accuracy. Evaluating the model with the test data leads to an accuracy of 51%. Not great but not too bad considering the highest accuracy is 56%.</p><h3><strong>Problem 2:</strong></h3><p>Problem 2 says to use the same technique but to change the length of the binary string to a random length from 1 to 50. We facilitate this change by simply adding an extra line to generate a random integer from 1 to 50 and use that as the length rather than the constant 50 we also add padding in front to convert all lengths to 50</p><pre>def gen_data(size=100000):</pre><pre>X_data_1 = []</pre><pre>Y_data_1 = []</pre><pre>for i in range(size):</pre><pre>length = random.randint(1, 50)</pre><pre>data = np.random.randint(2, size=(1, length)).astype(&quot;float32&quot;)</pre><pre>data = pad_sequences(data, maxlen=50, dtype=&#39;float32&#39;, padding=&#39;pre&#39;)</pre><pre>X_data_1.append(data)</pre><pre>labels = [0 if np.sum(X_data_1[i])%2 == 0 else 1]</pre><pre>Y_data_1.append(labels)</pre><pre>return X_data_1, Y_data_1</pre><p>We use the same LSTM model that we used previously to facilitate comparison between them.</p><pre>model = Sequential([</pre><pre>LSTM(32, return_sequences=True, activation=&#39;sigmoid&#39;, input_shape=(1, 50)),</pre><pre>LSTM(64, return_sequences=True, activation=&#39;sigmoid&#39;),</pre><pre>Dense(1, activation=&#39;sigmoid&#39;)</pre><pre>])</pre><p>Using the same techniques we split the data</p><pre>split_size = 100000 * 0.20</pre><pre>X_train = X_data1[split_size:]</pre><pre>X_test = X_data1[:split_size]</pre><pre>Y_train = Y_data1[split_size:]</pre><pre>Y_test = Y_data1[:split_size]</pre><p>And also compile the model</p><pre>model.compile(&#39;adam&#39;, loss=&#39;binary_crossentropy&#39;, metrics=[&#39;acc&#39;])</pre><p>And also normalize the data and convert it into numpy arrays</p><pre>X_train = np.asarray(X_train)</pre><pre>norm = np.linalg.norm(X_train)<br>normal_array = X_train/norm<br>print(normal_array)</pre><p>We then train the model</p><pre>history = model.fit(X_train, Y_train, epochs=50, batch_size=32, shuffle=True)</pre><p>Again we plot and analyze the performance of the model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*9h8S0LbkA2Tqd_Z1njKLaA.png" /><figcaption>Author’s Image For Loss And Accuracy of 2nd model</figcaption></figure><p>This time the model reaches an accuracy of almost 60% and when evaluated performed at an accuracy of 57% which is great!</p><p>This however is a very impractical way to solve the problem which would easily be solved using a dense neural network or even a simple recurrent neural network rather than a more complex LSTM and the only reason I solved it this way was because it was specifically requested in the problem.</p><p>Code For the Project: <a href="https://github.com/arnavdantuluri/XOROpenAi.git">https://github.com/arnavdantuluri/XOROpenAi.git</a></p><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67d8dc58e75a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>