<?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 Attyuttam Saha on Medium]]></title>
        <description><![CDATA[Stories by Attyuttam Saha on Medium]]></description>
        <link>https://medium.com/@attyuttam?source=rss-3c7286668559------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Des9h-v7Dz2r5M1i-pD9Sg.jpeg</url>
            <title>Stories by Attyuttam Saha on Medium</title>
            <link>https://medium.com/@attyuttam?source=rss-3c7286668559------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 20:59:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@attyuttam/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[Event-Driven Microservices using Spring Cloud Stream and Web Sockets]]></title>
            <link>https://medium.com/codex/event-driven-microservices-using-spring-cloud-stream-and-web-sockets-ee7c8921aa4f?source=rss-3c7286668559------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee7c8921aa4f</guid>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[topics]]></category>
            <category><![CDATA[real-time-communication]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[queue]]></category>
            <dc:creator><![CDATA[Attyuttam Saha]]></dc:creator>
            <pubDate>Fri, 30 Jul 2021 05:35:26 GMT</pubDate>
            <atom:updated>2021-08-03T04:04:29.334Z</atom:updated>
            <content:encoded><![CDATA[<h4>PART 1: THE FUNDAMENTAL CONCEPTS</h4><p>Being a programming enthusiast, we all are pretty hyped with new technologies that seem to be coming endlessly every day and one such buzz is <strong><em>Event-Driven Microservices </em></strong>which ensures that your system is more de-coupled and microservices are more independent. This sounds pretty cool but implementing it and understanding it becomes a real pain. So, I created a simple full-stack application that serves you real-time news using this concept and my job was eased up thanks to the beautiful libraries provided by Spring and React JS.</p><p>These are the primary things that I will be talking about in this post:</p><ul><li>Microservices</li><li>Event Driven Architecture</li><li>Queues and topics</li><li>Docker basics</li><li>Spring Cloud Stream</li><li>Web Socket using STOMP(Simple Text Oriented Messaging Protocol)</li></ul><p>My primary goal is to build a event driven architecture for communication between microservices and I will be using Spring Boot and React JS for this purpose and I assume that you have a pretty good understanding about Spring Boot and a yay bit about React JS will suffice.</p><h3>Microservices</h3><p>According to <a href="https://en.wikipedia.org/wiki/Microservices">Wikipedia</a>:</p><blockquote>A microservice is not a layer within a monolithic application (example, the web controller, or the backend-for-frontend). Rather it is a self-contained piece of business functionality with clear interfaces, and may, through its own internal components, implement a layered architecture. From a strategy perspective, microservices architecture essentially follows the <a href="https://en.wikipedia.org/wiki/Unix_philosophy">Unix philosophy</a> of “Do one thing and do it well”.</blockquote><p>The major advantages of microservices are:</p><ul><li>Microservices are highly maintainable</li><li>Can easily be tested</li><li>Microservices are loosely coupled as they are independent services dedicated towards performing a single well-defined task and each microservice can be deployed independently.</li></ul><p>Using microservices not only ensures that the delivery of complex application happens pretty smooth and fast in several iterations but it also ensures that the application can remain technology independent and changing from one tech stack to other does not become a nightmare, this helps an application to always remain up-to-date.</p><h3>Event Driven Architecture</h3><p>According to <a href="https://en.wikipedia.org/wiki/Event-driven_architecture">Wikipedia</a>:</p><blockquote><strong>Event-driven architecture</strong> (<strong>EDA</strong>) is a <a href="https://en.wikipedia.org/wiki/Software_architecture">software architecture</a> paradigm promoting the production, detection, consumption of, and reaction to <a href="https://en.wikipedia.org/wiki/Event_(computing)">events</a>.</blockquote><p>Speaking in simple terms, when we talk about EDA, we can think of a picture where we have say multiple microservices which needs to talk to each other and they do this by using something called <strong><em>events</em></strong>.</p><p>Now what are <strong><em>events </em></strong>?</p><p>An event can be defined as an indicator of change of state. So, the microservices act upon a change which it receives from another microservice. For example, when you click a button, an action is performed so the click can be considered as an event.</p><p>According to <a href="https://www.redhat.com/en/topics/integration/what-is-event-driven-architecture">RedHat</a>, the benefits of event driven architecture is:</p><blockquote>An event-driven architecture can help organizations achieve a flexible system that can adapt to changes and make decisions in real time. Real-time situational awareness means that business decisions, whether manual or automated, can be made using all of the available data that reflects the current state of your systems.</blockquote><p><em>I will be providing a diagram for visualizing right after I’m done with the next topic.</em></p><h3>Queues and Topics</h3><p>Messaging queues and topics are basically components into which we can put some messages and from which we can read messages. They both have some fundamental difference in characteristics.</p><p>Let us visualize the same:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FznH7pU72e2isQW0VT2cVw.png" /><figcaption>Message put into the queue can only be read by a single consumer</figcaption></figure><p>So, in case of queues, when a message producer puts some message into the queue, only one consumer can read the message and there can only be one subscriber to a messaging queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*odW8RRDul3_E5CI5D86v_Q.png" /><figcaption>Message put into the queue can only be read by a multiple consumers</figcaption></figure><p>On the other hand, message put onto a topic by the producer can be read by several consumers as multiple consumers can subscribe to a single topic.</p><h3>The entire picture of Event Driven Microservices</h3><p>Now, we have the idea of events and how is it supposed to be used in event driven architecture paradigm and also the fundamental concepts of queues and topics.</p><p>If we recall, in <strong><em>Event Driven Microservices</em></strong>, a microservice produces an event which when received by the desired microservice(s), the receiving microservice performs some operation and may further produce an event or not and this is the basic law of interaction in an event driven architecture paradigm.</p><p>So, we use queues and topics to enable the exchange of events between microservices and since microservices are subscribed to queues and topics, whenever there’s an event put on the messaging service, the microservice gets notified right then and performs the desired activity without any external invocation.</p><p>Now, according to <a href="https://www.redhat.com/en/topics/integration/what-is-event-driven-architecture">RedHat</a>, EDA may either be based on pub/sub model or event streaming model, but as in the project we follow a pub/sub model, let us visualize the pub/sub model of EDA (the <strong><em>indian-news</em></strong> application that we are going to be build):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DWt9OxKrvt1tVWt7RZBtXA.png" /><figcaption>The Indian News Application based on Event Driven Architecture</figcaption></figure><p>So, now as we will be diving further into the workings of the application, it is supposedly a good time to talk about the basics of docker, spring cloud stream and web sockets.</p><h3>Docker</h3><p>Docker can be thought of as a version control system for your app’s operating system. Using Docker you can run your application on your laptop in an environment that has the same configuration as that of your server in which the app is going to run in production.</p><p>As I myself am pretty new to this technology, I will talk in terms of a beginner’s understanding and keeping that in mind, we can simply think that we can use docker when we want to deploy an application or a tool in an isolated environment with all the dependencies installed without bothering ourselves to setup the dependencies in our local environment.</p><p>Please note that Apache Kafka acts as a queue as well as a topic, for more detail please check out <a href="https://abhishek1987.medium.com/kafka-is-it-a-topic-or-a-queue-30c85386afd6"><strong><em>this awesome article</em></strong></a> by <a href="https://medium.com/u/47a6bae243a3">Abhishek Gupta</a>.</p><p><strong><em>In my case, as my app needed to run the Kafka topic, using Docker helped to run the server to host the Kafka topic in an isolated environment without having to setup any configuration in my system.</em></strong></p><p>So, I believe you could grasp why I had to use docker in my project.</p><p>Before moving to the usage of Docker, it is essential to understand about Docker objects:</p><ul><li>Container Image</li><li>Container</li></ul><h4>Container Image</h4><p>According to Docker’s <a href="https://www.docker.com/resources/what-container">documentation</a>:</p><blockquote>A Docker container image is a lightweight, standalone, executable package of software that includes everything needed to run an application: code, runtime, system tools, system libraries and settings.</blockquote><p>A <strong><em>container image</em></strong> is basically a template which provides all the details of the software, configuration tools etc. and this image can be executed to develop an isolated filesystem.</p><h4>Container</h4><p>According to Docker’s <a href="https://www.docker.com/resources/what-container">documentation</a>:</p><blockquote>A container is a standard unit of software that packages up code and all its dependencies so the application runs quickly and reliably from one computing environment to another.</blockquote><p>A <strong><em>container </em></strong>is simply another process in your machine that has been isolated from all the other processes in your machine.</p><p>Available for both Linux and Windows-based applications, containerized software will always run the same, regardless of the infrastructure. Containers isolate software from its environment and ensure that it works uniformly despite differences for instance between development and staging.</p><h4>Relation between Container and Container Image</h4><p>The definitions are albeit pretty solid but difficult to understand right, it becomes a bit more simpler to understand them when you get to know the relation between them.</p><p>When running a <strong><em>container</em></strong>, it uses an isolated filesystem. This custom filesystem is provided by a <strong><em>container image</em></strong>. Since the image contains the container’s filesystem, it must contain everything needed to run an application — all dependencies, configuration, scripts, binaries, etc. The image also contains other configuration for the container, such as environment variables, a default command to run, and other metadata.</p><p>I use the following three points to relate <strong><em>images</em></strong> and <strong><em>containers</em></strong>:</p><ul><li>An <strong><em>Image</em></strong> is a read-only template with instructions for creating a Docker <strong><em>container.</em></strong></li><li>A <strong><em>Container</em></strong> is the runnable instance of a <strong><em>Image</em></strong>.</li><li><strong><em>Images</em></strong> become <strong><em>Containers </em></strong>at runtime and in the case of Docker <strong><em>containers</em></strong> — <strong><em>Images</em></strong> become <strong><em>Containers</em></strong> when they run on <a href="https://www.docker.com/products/container-runtime"><strong><em>Docker Engine</em></strong></a><strong><em>.</em></strong></li></ul><p><strong><em>Please Note:</em></strong> The terms <em>Container Image</em> and <em>Image </em>have been used interchangeably but both represent the same thing.</p><h4>Docker Compose</h4><p>Although we can build containers and run them one command at a time but the easiest way is to use <strong><em>docker compose</em></strong> as with this, all we need is to create a YAML file and then with a single command you can create an entire environment and bring it down as well.</p><p>The advantage is all your requirements for the environment is documented in a single file and others can contribute to that as well.</p><p>Now, we have understood the basics of docker but as this post is more focused on explaining the event driven architecture, I will not delve into the docker setup, explanation of the YAML file for docker etc., feel free to comment your thoughts and doubts on the post if you fail to understand the concepts when I will be explaining the code in Part 2 of this post.</p><h3>Spring Cloud Stream</h3><p>According to the <a href="https://spring.io/projects/spring-cloud-stream">Spring docs</a>:</p><blockquote>Spring Cloud Stream is a framework for building highly scalable event-driven microservices connected with shared messaging systems.</blockquote><blockquote>The framework provides a flexible programming model built on already established and familiar Spring idioms and best practices, including support for persistent pub/sub semantics, consumer groups, and stateful partitions.</blockquote><p>For a simple understanding of Spring Cloud Stream(SCSt), Oleg Zhurakousky sums it up pretty well in his <a href="https://spring.io/blog/2019/10/14/spring-cloud-stream-demystified-and-simplified"><em>blog</em></a>:</p><blockquote>SCSt has always been about pure microservices and binding them to <em>sources</em> and <em>targets</em> of data (i.e., messaging systems) . Simple as that.</blockquote><blockquote>If you abstract yourself far enough from knowing the internals of SCSt, you quickly realize that it is really a binding and activation framework. It binds a piece of code (provided by the user) to source/target of data exposed by the binder and activates such code according to binder implementation (for example, message arrival and so on). That is pretty much it.</blockquote><p>So, SCSt is basically a framework provided by spring that abstracts the boiler plate code to setup the messaging service, so that the user can focus only on the business logic and put it on the queue/topic or read from it without writing too much of code to setup the messaging system. SCSt is thus a flexible messaging abstraction that takes care of the complex messaging platform integration so you can concentrate on writing simple clean business logic.</p><p>The core building blocks of Spring Cloud Stream are:</p><ul><li><strong><em>Destination Binders</em></strong>: Components responsible to provide integration with the external messaging systems.</li><li><strong><em>Destination Bindings</em></strong>: Bridge between the external messaging systems and application code (producer/consumer) provided by the end user.</li><li><strong><em>Message</em></strong>: The canonical data structure used by producers and consumers to communicate with <em>Destination Binders </em>(and thus other applications via external messaging systems).</li></ul><p>We will be using <strong><em>Apache Kafka Binder</em></strong> in our application for interaction with the queue.</p><h3>Web Sockets using STOMP</h3><p>Web Sockets provided by spring is a <strong><em>full-duplex, two-way persistent communication scheme</em></strong> between a web browser and a server. The pipeline of communication established by a web socket remains connected until the client or the server decided to close the connection.</p><p>WebSocket is a thin, lightweight layer above TCP and it makes it suitable for using <strong><em>subprotocols</em></strong> to embed messages. One of the subprotocols that we will be using to establish the two-way connection is <a href="https://en.wikipedia.org/wiki/Streaming_Text_Oriented_Messaging_Protocol">STOMP</a>.</p><p>According to <a href="https://docs.spring.io/spring-framework/docs/4.3.x/spring-framework-reference/html/websocket.html#websocket-stomp-overview">Spring docs</a>:</p><blockquote><a href="https://stomp.github.io/stomp-specification-1.2.html#Abstract">STOMP</a> is a simple text-oriented messaging protocol that was originally created for scripting languages such as Ruby, Python, and Perl to connect to enterprise message brokers. It is designed to address a subset of commonly used messaging patterns. STOMP can be used over any reliable 2-way streaming network protocol such as TCP and WebSocket. Although STOMP is a text-oriented protocol, the payload of messages can be either text or binary.</blockquote><p>You can learn more about WebSockets and STOMP from the <a href="https://docs.spring.io/spring-framework/docs/4.3.x/spring-framework-reference/html/websocket.html#websocket-stomp-overview">Spring docs</a>.</p><h3>End of Part 1</h3><p>This part basically focuses on the fundamental concepts that I will be using to build the application and since there was quite a lot to explain even for the simple basics, I decided to dedicate one single post for the same. Please feel free to comment if you find any discrepancies or your thoughts.</p><p><a href="https://attyuttam.medium.com/event-driven-microservices-using-spring-cloud-stream-and-web-sockets-e93fe5fbe7d4"><strong><em>Go to Part2.</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee7c8921aa4f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/event-driven-microservices-using-spring-cloud-stream-and-web-sockets-ee7c8921aa4f">Event-Driven Microservices using Spring Cloud Stream and Web Sockets</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Event-Driven Microservices using Spring Cloud Stream and Web Sockets]]></title>
            <link>https://medium.com/javarevisited/event-driven-microservices-using-spring-cloud-stream-and-web-sockets-e93fe5fbe7d4?source=rss-3c7286668559------2</link>
            <guid isPermaLink="false">https://medium.com/p/e93fe5fbe7d4</guid>
            <category><![CDATA[kafka-streams]]></category>
            <category><![CDATA[messaging-platforms]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-cloud-stream]]></category>
            <dc:creator><![CDATA[Attyuttam Saha]]></dc:creator>
            <pubDate>Fri, 30 Jul 2021 05:34:19 GMT</pubDate>
            <atom:updated>2021-08-18T12:08:28.026Z</atom:updated>
            <content:encoded><![CDATA[<p>PART 2: THE IMPLEMENTATION</p><p><a href="https://attyuttam.medium.com/event-driven-microservices-using-spring-cloud-stream-and-web-sockets-ee7c8921aa4f"><strong><em>Go to Part 1</em></strong></a></p><p>I believe you have had the time to go through the concepts I had talked about in part 1 of this 2 part article, if not do check that out ! So, without further ado, let’s jump straight into what’s cooking.</p><p>The application<strong><em> Indian-news </em></strong>has two microservices that interact with each other. One of them is the <strong><em>news-app</em></strong> microservice which serves as the backend and is responsible for talking to the third party <a href="https://newsapi.org/s/india-news-api"><em>Google news API</em></a> to fetch the live news and send them over to the front end microservice which is the <strong><em>news-app-ui </em></strong>microservice.</p><p>Also, since this is an advanced spring topic, I am assuming that you are already familiar with <a href="https://medium.com/javarevisited/10-best-online-courses-to-learn-spring-framework-in-2020-f7f73599c2fd">Spring</a> and <a href="https://medium.com/javarevisited/10-free-spring-boot-tutorials-and-courses-for-java-developers-53dfe084587e">Spring Boot</a>, so I will just be talking about the concepts of <strong><em>Spring Cloud Stream</em></strong> and <strong><em>Web Sockets</em></strong> and how they enable us to build an<strong><em> Event-Driven Architecture</em></strong>.</p><p>Let us try and look at the working of the microservices.</p><h3><strong>Before you start</strong></h3><p>Please ensure that you have the following applications installed in your system:</p><ol><li><a href="https://adoptopenjdk.net/">Java 8</a></li><li><a href="https://docs.docker.com/docker-for-mac/install/">Docker</a> (where we’ll run RabbitMQ and Kafka locally)</li><li><a href="https://git-scm.com/book/en/v2/Getting-Started-Installing-Git">Git</a> (optional)</li><li><a href="https://medium.com/javarevisited/6-free-courses-to-learn-bash-shell-scripting-in-linux-and-unix-a50461ecd4fe?source=---------6------------------">Bash </a>(assumed, although alternatives could work)</li><li><a href="https://javarevisited.blogspot.com/2018/01/top-5-nodejs-and-express-js-online-courses-for-web-developers.html">npm </a>to run the React application</li></ol><h3>Project Structure</h3><p>Let’s check out the project structure</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*Gh11FnxUTwt_7sxoJ7SnhA.png" /><figcaption>The root project structure</figcaption></figure><figure><a href="https://javarevisited.blogspot.com/2018/08/top-5-react-js-and-redux-courses-to-learn-online.html#axzz5r06B3egD"><img alt="" src="https://cdn-images-1.medium.com/max/332/1*NfF3JYmorg7F5FiqLXyMNg.png" /></a><figcaption>news-app project structure</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*9yMcyA3Bft2oohmEvcIiUA.png" /><figcaption>news-app-ui project structure</figcaption></figure><p>Now, the news-app-ui microservice has a backend built using <a href="https://medium.com/javarevisited/10-advanced-spring-boot-courses-for-experienced-java-developers-5e57606816bd?source=collection_home---4------0-----------------------">spring boot</a> and a <a href="https://medium.com/javarevisited/6-best-frontend-development-courses-for-beginners-to-learn-in-2021-f2772157864">frontend </a>that provides a simple user interface to provide the user with the real-time news update.</p><p>Let us also look at the project structure of both parts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*HZm0Z1gcJWOwRmZkrBe8Iw.png" /><figcaption>backend project structure for news-app-ui</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*EHtdCdp7FE7rNJ4qn7VlBw.png" /><figcaption>front-end project structure for news-app-ui</figcaption></figure><p>Yeah, there’s nothing much on the UI side, I just wanted to display the news and nothing fancy but you can spread your wings!</p><h3>Running the application</h3><h4>1. First, clone the code repository from GitHub.</h4><pre>git clone <a href="https://github.com/Attyuttam/indian-news.git">https://github.com/Attyuttam/indian-news.git</a></pre><h4>2. Start the messaging servers</h4><p>Go to the folder <strong><em>indian-news</em></strong> and run the following command:</p><pre>./start-servers.sh</pre><h4>3. Get the API key and paste in the application.properties file of news-app</h4><p>You can get your API key from the <a href="https://newsapi.org/s/india-news-api">Google News API</a> after logging in using your Gmail id.</p><p>After you got your API key just replace the text <em>YOUR GOOGLE NEWS API KEY HERE</em> in the code mentioned below with the API key you got.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eec3d46dc0f2d2aa933498a9deaf0d0f/href">https://medium.com/media/eec3d46dc0f2d2aa933498a9deaf0d0f/href</a></iframe><h4>4. Run the news-app to get the news updates</h4><p>Go to the <strong><em>news-app</em></strong> folder and run the following command:</p><pre>mvn clean package spring-boot:run -DskipTests=true</pre><h4>5. Starting up the front end news-app-ui</h4><p>Go to the <strong><em>news-app-ui</em></strong> folder and run the following command:</p><pre>mvn clean package spring-boot:run -DskipTests=true</pre><p>Then go inside <strong><em>news-app-ui/main/ui </em></strong>and run the following command:</p><pre>npm start</pre><p>Please note that in case you are running this for the first time, we will have to ensure that all the necessary npm packages need to be installed. So, run the following command in the folder <strong><em>news-app-ui/main/ui</em></strong>:</p><pre>npm install</pre><p>And just to be sure install the stomp package as well using the following command:</p><pre>npm i @stomp/stompjs</pre><p>And once your app starts running, go to <a href="http://localhost:3000/">http://localhost:3000</a> in your web browser and you can see the news like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t6HoUl_owO4h69MPf54a7w.png" /><figcaption>The Indian News App display</figcaption></figure><h4>6. Stopping the application</h4><p>To stop the servers, just closing the bash or typing Ctrl+C will not work, you would rather have to run the following command at the root folder <strong><em>indian-news</em></strong>:</p><pre>./stop-servers.sh</pre><h3>news-app</h3><p>This microservice is built using spring boot and serves as the backend of the application which is responsible for fetch live news from the third party <a href="https://newsapi.org/s/india-news-api"><em>Google news API</em></a><em> </em>and then puts them on the <a href="https://medium.com/javarevisited/top-10-apache-kafka-online-training-courses-and-certifications-621f3c13b38c">Kafka topic</a> which is facilitated by <a href="https://spring.io/projects/spring-cloud-stream"><em>Spring Cloud Stream</em></a>.</p><p>The news-app reads live news from the third-party API by hitting their server to fetch the latest news every hour and this ensures that the user of this application gets to read live news throughout the day.</p><p>And as a programmer, if you think 1 hour is way too long a time, you can always change it to the count of seconds as well.</p><h3>How does news app work?</h3><p>Let us check the dependencies we would be needing in pom.xml file</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fbb23ada56a09e83b821aa42849512a/href">https://medium.com/media/5fbb23ada56a09e83b821aa42849512a/href</a></iframe><p>As you can see, we are importing the <em>spring-cloud-stream</em> dependency and as we are only going to use <a href="https://javarevisited.blogspot.com/2018/04/top-5-apache-kafka-course-to-learn.html#axzz6kZHuJeAZ">Kafka </a>for communication, we set the profile as Kafka by default and thus import the <em>spring-cloud-stream-binder-kafka</em> dependency for performing all the operations on the Kafka topic.</p><p>For the <strong><em>news-app</em></strong> <a href="https://medium.com/javarevisited/7-free-microservices-courses-for-java-programmers-c9b2f3a2ea7d">microservice</a>, we are using the Spring Cloud Stream v2.1 — <a href="https://cloud.spring.io/spring-cloud-stream/reference/html/spring-cloud-stream.html#spring_cloud_function">Spring Cloud Function support</a>. With this feature, all that’s required to get the NewsAppApplication microservice to act as a source of News messages is to declare a @Bean the method which generates and returns a Supplier&lt;&gt;. In this case it’s a Supplier of type News. The function method code looks something like this ( You can find this in the NewsProducer component)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1fa3d1b4bb8f936bfdc5410d13c1233/href">https://medium.com/media/c1fa3d1b4bb8f936bfdc5410d13c1233/href</a></iframe><p>Supplier&lt;&gt; is a Java function data type. Because there is only one @Bean method that returns this type, <a href="https://medium.com/javarevisited/5-best-courses-to-learn-spring-cloud-and-microservices-1ddea1af7012"><strong><em>Spring Cloud Stream</em></strong> </a>knows exactly what to do next. By default, it will trigger this function once every second and send the result to the default MessageChannel named <strong><em>output.</em></strong></p><p>We can explicitly mention this bean and the MessageChannel(here its news_output) as well by setting the property like the one shown below ( out method name is supplyNews):</p><pre>spring.cloud.stream.function.bindings.supplyNews-out-0=news_output</pre><p>The googleNewsServicethat you can see in the Supplier&lt;&gt; is the <a href="https://cloud.spring.io/spring-cloud-openfeign/reference/html/"><strong><em>feign client</em></strong></a><strong><em> </em></strong>responsible for making the call to the third party <a href="https://newsapi.org/s/india-news-api"><strong><em>Google News API service</em></strong></a>.</p><p>What’s nice about this method is that it only contains business logic so you can test it using a regular unit test. Also, in this method, you can apply your logic to play with the message before you put it onto the Kafka topic, thus it also acts as an intermediary before putting the message onto the Kafka topic.</p><p>We could use the spring.cloud.function.definition property in the application.properties file to explicitly declare which function bean we want to be bound to binding destinations - but for cases when you only have single @Bean defined, this is not necessary.</p><p>Also, since the default polling interval is one second but I have decided to poll at every hour, I have set the interval as 1 hour by setting the spring.integration.poller.fixed-delay property in the application.properties file.</p><p>Well, that’s the magic of <a href="https://medium.com/hackernoon/top-5-spring-boot-and-spring-cloud-books-for-java-developers-75df155dcedc?source=---------23------------------"><strong><em>Spring Cloud Stream</em></strong></a>, it basically extracted the concern of setting up the messaging environment from you and now all you are concerned with is the business logic.</p><p>You can see the entire code for the <strong><em>news-app</em></strong> microservice <a href="https://github.com/Attyuttam/indian-news/tree/master/news-app"><em>here</em></a>.</p><h3>news-app-ui</h3><p>The major tasks of this microservice can be divided into two parts:</p><ul><li>Receiving the data from the Kafka topic</li><li>Display it on the UI in real time</li></ul><p>Before we jump into understanding the first task, please ensure that you have the same dependencies(versions might differ) in your pom.xml file as well:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d512cc5e7cfbd4a2e0de9787654ec4e7/href">https://medium.com/media/d512cc5e7cfbd4a2e0de9787654ec4e7/href</a></iframe><p>Let us try to understand the first task.</p><p>Now, all we need to take care of in the first task is to ensure that we receive the events from the <strong><em>news-app</em></strong> properly. For this purpose, we set up a SubscribableChannelwhich shall be responsible for receiving the events from the source. This is how we do it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6249171429451c85e0733f46549bbfe5/href">https://medium.com/media/6249171429451c85e0733f46549bbfe5/href</a></iframe><p>But now a relevant question that comes to your mind is, how is the application supposed to know that this component is responsible for providing the channel to listen to the upcoming events. Well, the annotation <strong><em>@EnableBinding</em></strong> comes to our help.</p><p>This NewsProcessor interface is first referenced in the @SpringBootApplication class (NewsAppUiApplication.java) as a parameter of the @EnableBinding() annotation as you can see below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfd0e8be5d9b83c537227ebab8a24cbb/href">https://medium.com/media/cfd0e8be5d9b83c537227ebab8a24cbb/href</a></iframe><p>Now, once the channel is setup, we also setup one more component called the NewsUpdater which contains the method updateNews()which gets called automatically whenever a Newsevent comes onto the topic. It is able to do this because of the @StreamListenerannotation forNewsProcessor.NEWS_OUTPUTput on top of the method. Let us see it in the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d51ce47c7426d5b8007a84f2b7ec9a3/href">https://medium.com/media/8d51ce47c7426d5b8007a84f2b7ec9a3/href</a></iframe><p>Now, to understand what the updateNews() does, we will have to jump to the next task that the <strong><em>news-app-ui</em></strong> microservice does which is rendering the news data onto the UI in real time. To understand this, we will have to understand stocks, so check out the <strong><em>part 1 </em></strong>of this two part series to get a better idea on what web sockets are.</p><p>Let us see, how we set up Web Socket in <a href="https://medium.com/javarevisited/7-best-webflux-and-reactive-spring-boot-courses-for-java-programmers-33b7c6fa8995">Spring Boot</a> and <a href="https://medium.com/javarevisited/top-10-free-courses-to-learn-react-js-c14edbd3b35f">ReactJS</a>.</p><p>Since you have already ensured that the pom.xml file for news-app-ui is same for you as well, I will not delve into the details but just for double-checking, do ensure that you have the following two dependencies:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a246480c2542e5c69314cb063f27385/href">https://medium.com/media/8a246480c2542e5c69314cb063f27385/href</a></iframe><p>Now, let us create the Web Socket configuration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0bc2f722405d74203b1b6927ab4a565/href">https://medium.com/media/b0bc2f722405d74203b1b6927ab4a565/href</a></iframe><p>In the class above, by extending the WebSocketMessageBrokerConfigurer we are ensuring that we have the two methods configureMessageBroker()and registerStompEndpoints() available in the class WebSocketConfiguration.</p><p>The configureMessageBroker()first calls the enableSimpleBroker() method which creates a memory-based message broker to carry the message data onto destinations which have been prefixed with <strong><em>/topic</em></strong>. The other task it does id to add prefix <strong><em>/app</em></strong> using setApplicationDestinationPrefixes()so that the server can receive messages from client but in our case, we can remove that as we shall not be receiving any data from client.</p><p>In the method registerStompEndpoints()the addEndpoint()is responsible for registering a STOMP endpoint <strong><em>/ws-message</em></strong> over the WebSocket endpoint at the given mapping path.</p><p>So, that completes the backend part and now we will be configuring the frontend to have web sockets that ensure that the news updates are received and displayed on screen reactively without any refresh.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4749286155339fcd3845c5dfcb63312e/href">https://medium.com/media/4749286155339fcd3845c5dfcb63312e/href</a></iframe><p>So, that’s the basic UI created.</p><h3>Setting up the messaging server using Docker</h3><p>Well, now the messaging server is ready and all we need to do is to set up the messaging server so that the messages are well exchanged between the two <a href="https://medium.com/javarevisited/10-best-java-microservices-courses-with-spring-boot-and-spring-cloud-6d04556bdfed?source=rss-bb36d8439904------2&amp;utm_source=dlvr.it&amp;utm_medium=linkedin">microservices </a>over the Kafka topic. This is the <strong><em>docker-compose.yml</em></strong> file which will get executed once you run the <strong><em>./start-servers.sh</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87a01cd950b81a7b22869f0a6df83e64/href">https://medium.com/media/87a01cd950b81a7b22869f0a6df83e64/href</a></iframe><p>As you can see three services are created:</p><ol><li><strong><em>Kafdrop</em></strong> : Kafdrop is a web UI for viewing Kafka topics and browsing consumer groups<em>.</em> The tool displays information such as brokers, topics, partitions, consumers, and lets you view messages.</li><li><strong><em>Zookeeper</em></strong>: Kafka uses Zookeeper to manage service discovery for Kafka Brokers that form the cluster. Zookeeper basically manages the overall controller status in the cluster. It acts as a configuration repository, maintaining cluster metadata and also implementing the actual mechanics of the cluster.</li><li><strong><em>Kafka</em></strong>: This is essentially the Kafka cluster getting created. The Kafka cluster contains, Kafka brokers which are responsible for the exchange of data between Kafka producers and consumers.</li></ol><p>So, when all these are set up, we have a Kafka cluster ready which shall be listening to messages and will transfer them to the respective clients.</p><p>So, when you start the servers, the Kafdrop gives you a picture of all the topics which have been registered. And you can see the topic news_outputwhen you have started the <strong><em>news-app</em></strong> microservice.</p><p>Well, this is the magic that <strong><em>Spring Cloud Stream</em></strong> plays. In the code of either of the microservices, there isn’t one line of message broker specific(Apache Kafka/ Rabbit MQ/ Active MQ etc) code but due to the spring-cloud-stream-binder-kafka dependency, the microservices have been able to interact with the message brokers seamlessly, this makes it much easier to unit test the services and also to change the message brokers if necessary without any changes to the code.</p><p>Just go to http://localhost:9000 and you will be able to see this UI displaying the Apache Kafka cluster with the topics registered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Vy72GNGM-zb9eV5Y7wgew.png" /></figure><h3>Conclusion</h3><p>So, with this, we finish the second part of the two-part series and I hope you will successfully be able to create Event-Driven Microservices and run them in action. One additional thing you can do is to use SockJs for registering the STOMP endpoint which is a fun practice for you to do perhaps. Do comment if you have any questions or if you have a much better idea on implementing the same! Thanks for reading !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e93fe5fbe7d4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/javarevisited/event-driven-microservices-using-spring-cloud-stream-and-web-sockets-e93fe5fbe7d4">Event-Driven Microservices using Spring Cloud Stream and Web Sockets</a> was originally published in <a href="https://medium.com/javarevisited">Javarevisited</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Eager load when there’s Lazy loading involved]]></title>
            <link>https://attyuttam.medium.com/how-to-eager-load-when-theres-lazy-loading-involved-57753644834e?source=rss-3c7286668559------2</link>
            <guid isPermaLink="false">https://medium.com/p/57753644834e</guid>
            <category><![CDATA[eager-loading]]></category>
            <category><![CDATA[join]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[lazy-loading]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Attyuttam Saha]]></dc:creator>
            <pubDate>Sun, 11 Jul 2021 05:52:45 GMT</pubDate>
            <atom:updated>2021-08-04T02:34:33.067Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FfpwrHivUvjrYDVY" /><figcaption>Photo by <a href="https://unsplash.com/@mike_van_den_bos?utm_source=medium&amp;utm_medium=referral">Mike van den Bos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>More often than not we run into situations when although our entity has mappings of another entity with lazy loading but we need to use that entity and get all its associated mappings via eager loading. These situations mostly arise when we have a lot of database calls involved and we need to reduce the number of calls thereby reducing the total time taken. Fret not ! <strong><em>JOIN FETCH</em></strong> to the rescue !</p><p>So, let us have a look into the data first.</p><p>For this example, I have created two tables <strong><em>department</em></strong> and <strong><em>employee </em></strong>where a department can have many employees but an employee can belong to only one department.</p><p>Let us just have a glimpse into the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*PqXCwbjUrflGqHU8PMG8kg.png" /><figcaption>department table</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*fNO_hWx9zpSX9UgcQtOx3A.png" /><figcaption>employee table</figcaption></figure><p>Now let us look into the <strong><em>department</em></strong> and <strong><em>employee</em></strong> java classes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13e452731e2a2520b166b9782912d838/href">https://medium.com/media/13e452731e2a2520b166b9782912d838/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/412eee3c1a91c50039be406958223651/href">https://medium.com/media/412eee3c1a91c50039be406958223651/href</a></iframe><p>The main thing that I want you to focus on are the mappings and the fetch type. As we can see in the <strong><em>Department </em></strong>class the employees are mapped using a list in a one to many bi-directional mapping. This has been done using the <strong><em>@OneToMany</em></strong> annotation on the employeeList List and it is also crucial to note that the fetch type is lazy. Also, in the <strong><em>Employee </em></strong>class we are adding a <strong><em>@ManyToOne</em></strong> annotation on the department variable which associates an employee with their department.</p><p>So, before I dive into <strong><em>JOIN FETCH</em></strong>, I just want to touch upon an example of JOIN and from the console output, we can find out the number of calls being made.</p><p>When we use <strong><em>JOIN </em></strong>or the <a href="https://docs.spring.io/spring-data/jpa/docs/current/api/org/springframework/data/jpa/repository/JpaRepository.html#findAll--"><strong><em>findAll()</em></strong></a> method provided by JPA to get all the departments and their related users, we use the following ways:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca2146c9b0bbef8b15ee545c61d8133b/href">https://medium.com/media/ca2146c9b0bbef8b15ee545c61d8133b/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc63a3875a8a42eb452312344d718423/href">https://medium.com/media/cc63a3875a8a42eb452312344d718423/href</a></iframe><p>For both of the styles used, the Hibernate queries mentioned below gets generated.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f833fa13eef225c167aaa9bead51c760/href">https://medium.com/media/f833fa13eef225c167aaa9bead51c760/href</a></iframe><p>As we can see that first an SQL query is run to get all the departments and then for each of the department an SQL query is run to get the corresponding employees in that department.</p><p>Finally, the result, if shown using a controller shall look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a96e8a7c3ab891e0ad04c318e34fda35/href">https://medium.com/media/a96e8a7c3ab891e0ad04c318e34fda35/href</a></iframe><p>So, how to optimize this ?</p><p>Well by using <strong><em>JOIN FETCH</em></strong> !</p><p>So, <strong><em>JOIN FETCH</em></strong> basically removes all the extra calls to fetch all the employees of a particular department but does that in a single DB call !</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cb2bbc4aa1424de8717a6f39a1d7b1c/href">https://medium.com/media/8cb2bbc4aa1424de8717a6f39a1d7b1c/href</a></iframe><h3>Conclusion</h3><p>Thus, it is pretty clear that <strong><em>JOIN FETCH</em></strong> speeds up your DB calls and we can leverage this property of <strong><em>JOIN FETCH</em></strong> in situations where the association is of type <strong><em>LAZY </em></strong>but we need the data in an <strong><em>EAGER </em></strong>manner.</p><p>For the entire example written using spring boot check <a href="https://github.com/Attyuttam/join-fetch-example"><strong><em>this</em></strong></a> out !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57753644834e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Data Source Routing in Spring Boot using AbstractRoutingDataSource]]></title>
            <link>https://medium.com/swlh/dynamic-data-source-routing-using-abstractroutingdatasource-in-spring-boot-d6dbdd644072?source=rss-3c7286668559------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6dbdd644072</guid>
            <category><![CDATA[spring-data-jpa]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[awesome]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[multiple-datasources]]></category>
            <dc:creator><![CDATA[Attyuttam Saha]]></dc:creator>
            <pubDate>Tue, 06 Jul 2021 11:02:04 GMT</pubDate>
            <atom:updated>2021-07-06T11:02:30.636Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Zt06gc8z_RGvYDDK" /><figcaption>Photo by <a href="https://unsplash.com/@lucian_alexe?utm_source=medium&amp;utm_medium=referral">Lucian Alexe</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A very common use case that we generally get while building services is to enable multiple data sources in the same service where the connectivity to either of them is capable at run time with a single instance of the application running.</p><p>This problem is more commonly known as the <strong><em>multi tenant</em></strong> data architecture with a single application connecting to multiple data sources (There are 3 scenarios for multiple data sources but I will not be delving into that), although there are ways to create multiple entity managers etc and create multiple data sources but that requires a lot of code and too much of maintenance. So, to solve this problem <strong><em>spring-jdbc</em></strong> provides us with a beautiful concept called the <strong><em>AbstractRoutingDataSource</em></strong><em>.</em></p><p>The definition from Spring documentation:</p><blockquote>AbstractRoutingDataSource is an abstract <a href="https://docs.oracle.com/javase/8/docs/api/javax/sql/DataSource.html?is-external=true">DataSource </a>implementation that routes <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/jdbc/datasource/lookup/AbstractRoutingDataSource.html#getConnection--">getConnection()</a> calls to one of various target DataSources based on a lookup key. The latter is usually (but not necessarily) determined through some thread-bound transaction context.</blockquote><p>To put more concisely, there are four things that we need to implement dynamic data source routing using AbstractRoutingDataSource:</p><ol><li>A component that extends AbstractRoutingDataSource and is responsible to provide the list of datasources and also to provide the implementation of the <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/jdbc/datasource/lookup/AbstractRoutingDataSource.html#determineCurrentLookupKey--"><strong><em>determineCurrentLookupKey()</em></strong></a> method which will help in determining the current datasource.</li><li>A context holder component that determines the context which is better to be thread bound by using <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/ThreadLocal.html"><strong><em>Threadlocal </em></strong></a>so that the context is bound to the currently executing thread.</li><li>A context, generally an enum which serves as the lookup key to determine the current datasource.</li><li>A configuration class which create the primary datasource bean, the entity manager and the transaction bean.</li></ol><p>We are going to save employee data into the database where there will be only one table <strong><em>employee.</em></strong></p><p>Let’s jump into the code straightaway!</p><h3>Setting up the data sources using MySQL</h3><p>In MySQL, run these scripts to create the two databases each of which having a table employee having the same structure. These two different databases will serve as the two data sources for the application.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0df95032ba6f06cb70e126a44ade5da1/href">https://medium.com/media/0df95032ba6f06cb70e126a44ade5da1/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f86c36d389616af58f3b53f902c7698/href">https://medium.com/media/4f86c36d389616af58f3b53f902c7698/href</a></iframe><h3>1. The Maven Dependencies</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/804b5ebaa2ace3f880224ce96bb89249/href">https://medium.com/media/804b5ebaa2ace3f880224ce96bb89249/href</a></iframe><h3>2. The Project Structure:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*X2_yiug4COCPp45GNtPIWw.png" /><figcaption>Spring boot project structure</figcaption></figure><h3>3. The Employee Entity</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5498e74418c0d141471c0698164cb8e8/href">https://medium.com/media/5498e74418c0d141471c0698164cb8e8/href</a></iframe><h3>4. The Employee Repository</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/229fec2f0fb11326d1cde5e874acfead/href">https://medium.com/media/229fec2f0fb11326d1cde5e874acfead/href</a></iframe><h3>5. The Employee Service</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a7019a5d27f44bb5b77ec43cb7fc78e/href">https://medium.com/media/3a7019a5d27f44bb5b77ec43cb7fc78e/href</a></iframe><h3>6. The application.properties file</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98b3326094767b22b11f1dfbda23a179/href">https://medium.com/media/98b3326094767b22b11f1dfbda23a179/href</a></iframe><h3>7. The Configuration file for the first data source</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc368d07cc62b0403c89a2ba9c50bb08/href">https://medium.com/media/dc368d07cc62b0403c89a2ba9c50bb08/href</a></iframe><h3>8. The Configuration file for the second data source</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6eda72094cfbeb8b780d245df946f89/href">https://medium.com/media/b6eda72094cfbeb8b780d245df946f89/href</a></iframe><h3>9. The Context</h3><p>The context file is represented as an <a href="https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html"><strong><em>enum </em></strong></a>which serves as the lookup key for a data source.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0b12ab15a568e4c6d94fe00be855c03/href">https://medium.com/media/f0b12ab15a568e4c6d94fe00be855c03/href</a></iframe><h3>10. The Context Holder</h3><p>The context holder is a component that serves as a store for the thread bound context. There are member methods which can be used to set, retrieve and delete the context.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3045181475ff255f074d96a99c1ea19b/href">https://medium.com/media/3045181475ff255f074d96a99c1ea19b/href</a></iframe><h3>11. The Component responsible for routing to the appropriate DataSource</h3><p>In this we create two methods:</p><ol><li><em>dataSourceTwoDataSource()</em></li><li><em>dataSourceOneDataSource()</em></li></ol><p>These two methods creates an object of DataSource type containing the configurations of the first and second datasource respectively. These methods are then used to set the list of target data sources to which the application can route to during run time.</p><p>The initialization of the target datasources are done in the constructor so that the target data sources are listed when the component is created. The listing is done using the <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/jdbc/datasource/lookup/AbstractRoutingDataSource.html#setTargetDataSources-java.util.Map-"><strong><em>setTargetDataSources()</em></strong></a> method which takes in a map of data source key to the DataSource object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9dff0112c060e095263998819ca8bacb/href">https://medium.com/media/9dff0112c060e095263998819ca8bacb/href</a></iframe><h3>12. The Data Source Configuration</h3><p>The DataSourceConfig file creates a DataSource bean which essentially returns the DataSourceRouting component that we had created earlier. It is due to this exact reason, we have added a <strong><em>@DependsOn </em></strong>annotation which ensures that the configuration bean is created once our routing DataSource is created.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cef7abae6653bb9beca61d8af71052ee/href">https://medium.com/media/cef7abae6653bb9beca61d8af71052ee/href</a></iframe><h3>13. The Controller</h3><p>In the controller I am taking the context as a path variable and then using the context holder to set the current data source context.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32f91c9d613a30b3e171b5ca8b45472b/href">https://medium.com/media/32f91c9d613a30b3e171b5ca8b45472b/href</a></iframe><h3>14. Running the application</h3><p>The runner class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2eb7e117a37eefdcdfbdeef65364ce81/href">https://medium.com/media/2eb7e117a37eefdcdfbdeef65364ce81/href</a></iframe><p>Once the application starts running,</p><p>To check the details of the first data source, go to <a href="http://localhost:8081/getEmployeeDetails/DATASOURCE_TWO">http://localhost:8081/getEmployeeDetails/DATASOURCE_O</a>NE</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*IoPSvkxFdM-SSzGYtZCRFA.png" /></figure><p>To check the details of the second data source, go to <a href="http://localhost:8081/getEmployeeDetails/DATASOURCE_TWO">http://localhost:8081/getEmployeeDetails/DATASOURCE_</a>TWO</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*CrFOkHBtuA-n06oi9sT3_w.png" /></figure><h3>Conclusion</h3><p>So, I have tried to explain the use case and how we will be using AbstractRoutingDataSource provided by Spring to elegantly solve the problem. You can go through the entire article and understand the nook and crannies on how it works and do comment if there are parts which you are confused about.</p><p>The code can be found <a href="https://github.com/Attyuttam/dynamic-datasource-routing-examples/tree/master/example3"><strong><em>here</em></strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6dbdd644072" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/dynamic-data-source-routing-using-abstractroutingdatasource-in-spring-boot-d6dbdd644072">Dynamic Data Source Routing in Spring Boot using AbstractRoutingDataSource</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generative Adversarial Networks using Pytorch]]></title>
            <link>https://attyuttam.medium.com/generative-adversarial-networks-using-pytorch-3ad31cc61ac8?source=rss-3c7286668559------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ad31cc61ac8</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[generative-adversarial]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[fashion-mnist]]></category>
            <dc:creator><![CDATA[Attyuttam Saha]]></dc:creator>
            <pubDate>Thu, 20 Aug 2020 04:08:40 GMT</pubDate>
            <atom:updated>2020-08-20T04:08:40.774Z</atom:updated>
            <content:encoded><![CDATA[<h4>Here I’ll be talking about GANs and how they can be used to generate images of fashionable items like shirts, shoes etc from the MNIST dataset and the code for doing this will be well explained and I shall be using PyTorch for this purpose.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*4BxXRNVKXU4GcAMm.jpg" /><figcaption>Image courtesy: <a href="https://www.liberaldictionary.com/adversary/">Liberal Dictionary</a></figcaption></figure><h3>A bit about GANs</h3><p>Now, I am assuming we all have a fair bit of knowledge with Deep Neural Networks and most of of the time we spend applying these concepts the use cases are generally like classification, predictions etc. Now, we know these tasks fall under the category of supervised learning for which DNNs are famous. But what we intend to achieve by using GANs is called <strong><em>Generative Modelling.</em></strong></p><p>According to Jason Brownlee in his <a href="https://machinelearningmastery.com/what-are-generative-adversarial-networks-gans/">article on GANs</a>:</p><blockquote>Generative modeling is an unsupervised learning task in machine learning that involves automatically discovering and learning the regularities or patterns in input data in such a way that the model can be used to generate or output new examples that plausibly could have been drawn from the original dataset</blockquote><p>Now, to create a GAN we need two different kinds of models: <strong><em>Generator Model</em></strong> and <strong><em>Discriminator Model</em></strong>.</p><p>The purpose of the Generator model is to generate new examples out of random input vectors provided to it, now how it does that, we are going to ponder on that pretty soon !</p><p>And the Discriminator is a simple classifier that takes input an image and classifies it into either a Fake image or a Real Image.</p><p>By Fake image I mean an image created by the Generator and by Real image I mean an image that has been provided from the dataset and the <strong>whole concept of GANs revolves around the generator trying to fool the discriminator !</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/0*HJA0zsfewzPNm4uQ.png" /><figcaption>The Generator Model. Picture by <a href="https://machinelearningmastery.com/what-are-generative-adversarial-networks-gans/">Jason Brownlee in Machine Learning Mastery</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/0*-S5pvWefqU7IS3gr.png" /><figcaption>The Discriminator Model. Picture by <a href="https://machinelearningmastery.com/what-are-generative-adversarial-networks-gans/">Jason Brownlee in Machine Learning Mastery</a></figcaption></figure><h3>Why is it called an Adversarial Network ?</h3><p>Now, as we shall be seeing in the code that the two models are trained in tandem to each other. The generator essentially creates a set of images and these are provided to the discriminator which tries to tell whether the given image is real or fake. As the discriminator is also being trained with inputs from the dataset, it becomes well trained in understanding what the real images are, hence, if the generator is successful in making the discriminator believe that the image generated by it is a real image, the generator has done a good job !</p><blockquote>We can think of the generator as being like a counterfeiter, trying to make fake money, and the discriminator as being like police, trying to allow legitimate money and catch counterfeit money. To succeed in this game, the counterfeiter must learn to make money that is indistinguishable from genuine money, and the generator network must learn to create samples that are drawn from the same distribution as the training data.</blockquote><blockquote>- <a href="https://arxiv.org/abs/1701.00160"><em>NIPS 2016 Tutorial: Generative Adversarial Networks</em></a><em>, 2016.</em></blockquote><p>Hence, both the models are trying to act as opponent to each other, the generator is trying to fool the discriminator and the discriminator is trying to avoid being fooled. Once the generator successfully fools the discriminator, our job is done ! Thus, both are adversaries to each other. Hence, the term <strong><em>adversarial</em></strong> comes into the picture.</p><h3>The entire architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/0*YdiuBFIPZZzHgS11.png" /><figcaption>The GAN. Picture by <a href="https://machinelearningmastery.com/what-are-generative-adversarial-networks-gans/">Jason Brownlee in Machine Learning Mastery</a></figcaption></figure><h3>The Code</h3><p>The code that I will be using is from a <a href="https://jovian.ml/aakashns/06b-anime-dcgan">notebook by Jovian.ml</a> and has also been inspired from <a href="https://medium.com/github.com/yunjey/pytorch-tutorial">this repository of PyTorch tutorials</a>.</p><p>I will also be using Jovian to save and commit the code and fret not as this shall not be blocker in your learning process as you can commit your code anywhere you want !</p><p>Let’s dive in !</p><h3>Imports and Data Loading</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F2%26cellId%3D2&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F2%26cellId%3D2&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/afc7f0bb87c9f3ec3a201b990336feef/href">https://medium.com/media/afc7f0bb87c9f3ec3a201b990336feef/href</a></iframe><p>In the code block above, all the necessary libraries are being imported and then the <strong><em>FashionMNIST </em></strong>dataset from <strong><em>torchvision.datasets </em></strong>has been used to download the Fashion MNIST dataset. In the process of downloading I am also converting the downloaded data into tensor and am also normalizing the images using the standard deviation and mean value of 0.5 which ensures that all the pixel values of the image range from -1 to 1. As this is a gray-scale image, hence there is only one channel because of which both the standard deviation and the mean value has one value each.</p><h3>Viewing the tensor</h3><p>We should see the data that we have downloaded and converted to tensor right !</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F2%26cellId%3D4&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F2%26cellId%3D4&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/a609b4b9a1517581f945a43e47410f5a/href">https://medium.com/media/a609b4b9a1517581f945a43e47410f5a/href</a></iframe><p>Here, I have printed the label of the first MNIST image and a part of the tensor and to ensure the range of pixel values in the image, I have also printed the minimum and the maximum pixel value and as expected its -1 and 1 respectively.</p><h3>Viewing the Image</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D6&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D6&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/545aa163dd09d26f532f5c6f57235e25/href">https://medium.com/media/545aa163dd09d26f532f5c6f57235e25/href</a></iframe><p>The code above is a helper method to de-normalize the image before viewing.</p><p>Now, let’s see one of the images from the dataset.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D7&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D7&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6b14f0fd7b57463039d9a1221cd2d09/href">https://medium.com/media/a6b14f0fd7b57463039d9a1221cd2d09/href</a></iframe><h3>Setting up the DataLoader</h3><p>Now, during training we would want the data to be loaded in batches and the training be done on a batch and then update the weights and stuff. To achieve this we use the data loader provided by PyTorch.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D9&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D9&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d9f60f27a9edef8776b6e37af738e9b/href">https://medium.com/media/4d9f60f27a9edef8776b6e37af738e9b/href</a></iframe><p>We also view the labels of all the images of the first batch and also one of the images of the first batch to ensure that the batch is getting properly loaded.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D10&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D10&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c6df9add731fba402b128e608fb95cd/href">https://medium.com/media/8c6df9add731fba402b128e608fb95cd/href</a></iframe><h3>Finding out the appropriate device</h3><p>Now, it is wise to use the GPU for image processing problems like this one but in case we don’t have one we might have to end up using the CPU. So, to ensure that the models get loaded onto the appropriate device, the following piece of code has been written.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D12&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D12&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/2233c0e791c1e0c612b68ca4d8ff3e7f/href">https://medium.com/media/2233c0e791c1e0c612b68ca4d8ff3e7f/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D13&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D13&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2cf59ac1de4214ce3ae9e61ee2ad3a7/href">https://medium.com/media/e2cf59ac1de4214ce3ae9e61ee2ad3a7/href</a></iframe><p>We can see that the device is of type cuda which means that currently the GPU is active. I have used the kaggle environment to run this piece of code.</p><h3>The Discriminator Model</h3><p>As explained above, the discriminator is a simple classifier that tries to distinguish between fake and real images. To perform a better classification we can definitely use a CNN model but in this case as the dataset is not that complicated, we are using a simple feed forward neural network, you can definitely try using a CNN to achieve much better results !</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D15&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D15&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/a97f57f32ee0812cc53218898db45914/href">https://medium.com/media/a97f57f32ee0812cc53218898db45914/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D16&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D16&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/82db32b329948cf0c409d23ef8ed3acb/href">https://medium.com/media/82db32b329948cf0c409d23ef8ed3acb/href</a></iframe><p>I have added in comments the steps that the Discriminator model has, so I am not doing redundant stuffs here :p</p><p>For readers who are not familiar with the concept of leaky ReLU. It differs from normal ReLU only by the fact that values less than 0 are not set to 0 but some factor of the number itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*x1YCh4nnfgNaIWgB" /><figcaption>Left: ReLU , Right: Leaky ReLU. Source: <a href="https://www.quora.com/What-is-leaky-ReLU">Quora answer by Daria Shamai</a></figcaption></figure><h3>The Generator Model</h3><p>The input to the generator model is random input vector also called a latent variable.</p><p>According to Jason Brownlee:</p><blockquote>We often refer to latent variables, or a latent space, as a projection or compression of a data distribution. That is, a latent space provides a compression or high-level concepts of the observed raw data such as the input data distribution. In the case of GANs, the generator model applies meaning to points in a chosen latent space, such that new points drawn from the latent space can be provided to the generator model as input and used to generate new and different output examples.</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D20&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D20&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/42639d7ef5f70e7daae7e5d56e7b0a50/href">https://medium.com/media/42639d7ef5f70e7daae7e5d56e7b0a50/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D21&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D21&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/057b007d63027a423a9e19a1aabb48ed/href">https://medium.com/media/057b007d63027a423a9e19a1aabb48ed/href</a></iframe><p>Now, one might think why did we use this new tanh() activation function in the end. What surprise element does it bring to the table ?!</p><p>Well, these explanations are provided in research papers and I have merely implemented them. Although, there’s an explanation provided in the paper by Alec Radford &amp; Luke Metz from indico Research and Soumith Chintala from Facebook AI Research titled <strong><em>Unsupervised representation learning with deep convolutional generative adversarial networks </em></strong>(<a href="https://arxiv.org/pdf/1511.06434.pdf]">https://arxiv.org/pdf/1511.06434.pdf]</a>)<strong><em> </em></strong>as:</p><blockquote>The ReLU activation (Nair &amp; Hinton, 2010) is used in the generator with the exception of the output layer which uses the Tanh function. We observed that using a bounded activation allowed the model to learn more quickly to saturate and cover the color space of the training distribution. Within the discriminator we found the leaky rectified activation (Maas et al., 2013) (Xu et al., 2015) to work well, especially for higher resolution modeling.</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D23&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D23&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf91443fa91f0bb61cc82b7982a987eb/href">https://medium.com/media/bf91443fa91f0bb61cc82b7982a987eb/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D24&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D24&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/69c55119952f776f5766886df296cd92/href">https://medium.com/media/69c55119952f776f5766886df296cd92/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D25&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D25&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/bf9dc5b8d14932097e2b0a5b30e49a6d/href">https://medium.com/media/bf9dc5b8d14932097e2b0a5b30e49a6d/href</a></iframe><h3>Loading models to appropriate device</h3><p>We had seen earlier how to load models and data to CPU/GPU. Now as we are done with defining the models, it is time for us to load the models onto the GPU.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D18&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D18&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/261255be031e2d22db4c6e47bfeee0a2/href">https://medium.com/media/261255be031e2d22db4c6e47bfeee0a2/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D27&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D27&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/8017bda949179fa58ae1def0fff05b2a/href">https://medium.com/media/8017bda949179fa58ae1def0fff05b2a/href</a></iframe><h3>Training the Discriminator</h3><p>As the discriminator is a binary classifier, so I will be using the binary cross entropy loss function to quantify the efficiency at which the discriminator is able to classify. Also, I will be using the Adam optimizer for performing the gradient descent.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D29&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D29&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/083b76d02522d655c5b24febb98b8ecd/href">https://medium.com/media/083b76d02522d655c5b24febb98b8ecd/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D31&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D31&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/23efac961f9c6ce6d3acf813a2ded73e/href">https://medium.com/media/23efac961f9c6ce6d3acf813a2ded73e/href</a></iframe><p>So, the comments are pretty explanatory but I will try to provide a picture of what’s really going on here.</p><p>So, essentially we would want the discriminator to classify all the images from the Fashion MNIST dataset as real and the ones from the generated dataset as fake so, we find the loss for the images from the MNIST dataset by setting the labels to be compared with in the loss function as 1 and vice versa for the images generated by the generator. After we have calculated the loss for both the real and fake set of images, we add the two losses as the net loss for the discriminator. You can also observe that only the gradients of the discriminator is being calculated and not that of the generator as in this piece of code we are only training the discriminator.</p><h3>Training the Generator</h3><p>The generator produces images, hence training it is a bit of a challenge. But, by using the discriminator as part of the loss function, you will see how easily we achieve this task.</p><p>Firstly, we generate a batch of images from the generator. Now, we pass these images to the discriminator but we set the labels to 1 to try to fool the discriminator into understanding that what we have passed to it are real images. This will tell us how far are the images generated by the generator from real images. We will then use the loss to update the weights of the generator.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D34&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D34&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/011e3f39025500545aedcbf6d830efd8/href">https://medium.com/media/011e3f39025500545aedcbf6d830efd8/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D35&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D35&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/3babeec734cfbacda12ea6b591fee1dc/href">https://medium.com/media/3babeec734cfbacda12ea6b591fee1dc/href</a></iframe><p>Again, we can observe that the weights of the generator are being updated, the weights of the discriminator remain intact and is not getting affected.</p><h3>Training the Model</h3><p>We will create a directory to save the intermediate results of the generator during training.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D37&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D37&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/92063c386707a7d6fa851b9c8b05b295/href">https://medium.com/media/92063c386707a7d6fa851b9c8b05b295/href</a></iframe><p>We will save a batch of real images into this directory. This is an unnecessary step and if you want, you can avoid this.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D39&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D39&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/6701a975eb5cb649a9ceabe9543e20d8/href">https://medium.com/media/6701a975eb5cb649a9ceabe9543e20d8/href</a></iframe><p>Now, the code for creating the directory to save intermediate images of the generator is done, we will now create a helper function to save the generated images into this directory.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D41&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D41&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/81af704d520073b1abd40f6e61a4b575/href">https://medium.com/media/81af704d520073b1abd40f6e61a4b575/href</a></iframe><p>Let’s start with the training.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D43&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D43&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/02db91cbfa5514f2f71e546565c9c6a5/href">https://medium.com/media/02db91cbfa5514f2f71e546565c9c6a5/href</a></iframe><h3>Saving checkpoints and viewing intermediate data</h3><p>Now, that the training is done, I have saved the model checkpoints as you can see the piece of code below:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D45&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D45&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2df42aef98fd9be07768431e750587b/href">https://medium.com/media/f2df42aef98fd9be07768431e750587b/href</a></iframe><p>Now, let us view some of the intermediate results:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D47&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D47&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba63288c0ac71cacec42d600cb899e75/href">https://medium.com/media/ba63288c0ac71cacec42d600cb899e75/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D48&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D48&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7a2ede4070daca8d112ef755ae4981f/href">https://medium.com/media/e7a2ede4070daca8d112ef755ae4981f/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D49&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D49&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbbd0e6fc41728d47962e05275a2e862/href">https://medium.com/media/bbbd0e6fc41728d47962e05275a2e862/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D50&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D50&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/16799e3c61ab6fd80443f400dfe45ac1/href">https://medium.com/media/16799e3c61ab6fd80443f400dfe45ac1/href</a></iframe><h3>Creating the learning video (additional)</h3><p>Now, as an addition, we can also create a video of the learning process where we collate all the intermediate images and put them on a video. We use opencv to achieve this.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D52&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D52&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4079ec283c45189ad1f60bad623a1ea/href">https://medium.com/media/d4079ec283c45189ad1f60bad623a1ea/href</a></iframe><h3>Viewing the losses and accuracies</h3><p>Our main aim is to ensure that the loss of the generator reduces overtime given that the loss of the discriminator does not become too high.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D54&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D54&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbc2130b81477023ea51a5aa6dd5d084/href">https://medium.com/media/bbc2130b81477023ea51a5aa6dd5d084/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D55&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D55&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/feb5e12b6e71f5b8d8c3eba3ff5c7bef/href">https://medium.com/media/feb5e12b6e71f5b8d8c3eba3ff5c7bef/href</a></iframe><h3>Save and Commit(additional)</h3><p>In this part I will be using Jovian.ml to save my code. Feel free to skip this part if you want to commit in some other platform.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D57&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D57&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/e600c240fb966db1a74831e18553ad0f/href">https://medium.com/media/e600c240fb966db1a74831e18553ad0f/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D58&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D58&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/b88bd5bd8ae9239ce8a48800ad9b865a/href">https://medium.com/media/b88bd5bd8ae9239ce8a48800ad9b865a/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D59&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F06-mnist-gan%2Fv%2F3%26cellId%3D59&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/941f0b5d6ddb8153d4d6abe8fb826f6c/href">https://medium.com/media/941f0b5d6ddb8153d4d6abe8fb826f6c/href</a></iframe><h3>Conclusion</h3><p>In this article, I have written about my understanding of GANs and have also provided the code for generating images from the fashion MNIST dataset. This code has been taken from one of the notebooks from Jovian.ml and I have used that code on the FashionMNIST dataset. I am also currently in the learning process so do drop a comment or mail me if you find any discrepancies. Thanks for reading, do not forget to throw a clap !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ad31cc61ac8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Colombian hand gesture for sign language classification]]></title>
            <link>https://attyuttam.medium.com/colombian-hand-gesture-for-sign-language-classification-d830ba7b706e?source=rss-3c7286668559------2</link>
            <guid isPermaLink="false">https://medium.com/p/d830ba7b706e</guid>
            <dc:creator><![CDATA[Attyuttam Saha]]></dc:creator>
            <pubDate>Fri, 14 Aug 2020 04:48:54 GMT</pubDate>
            <atom:updated>2020-08-14T04:48:54.343Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using residual networks and transfer learning to train a model to classify various hand gestures of sign language.</h4><p>In this article, I will dive straight into the code and its caveats and points to discuss on how I have approached this problem of classification. I will be providing notes and links to cases where explanation of a particular topic is required but I will try not to discuss much on theory.</p><h3>Importing Libraries</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D1&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D1&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9a0d02900466fa3b2e49b3953661735/href">https://medium.com/media/c9a0d02900466fa3b2e49b3953661735/href</a></iframe><p>These are the libraries that I have imported and I will be providing basic explanations as I will continue to use them. For more in-depth understanding please refer to their documentations which are easily available.</p><h3>Splitting into training and validation set and exploring the dataset</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D2&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D2&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/b29b1900a0d266f3d8a434db8216a0d5/href">https://medium.com/media/b29b1900a0d266f3d8a434db8216a0d5/href</a></iframe><p>In the code block above, I have done the following three things:</p><ol><li>Data augmentation</li><li>Splitting data into training and validation sets</li><li>Observing the length of the each set</li></ol><p>As the images are way too large in size, so processing is difficult, hence, I have resized the image into 32x32 pixels and before doing that, I have taken a random crop of 2500 from the image so that a bit of randomness is also thrown in. To ensure that the images are more random in nature, I have carried out the process of data augmentation by performing random crop, random vertical flip and random horizontal flip.</p><p>To ensure that the splitting of the datset into validation and test set is done randomly, I have used the <strong><em>random_split() </em></strong>method from <strong><em>torch.utils.data</em></strong> and to ensure that the random splitting is the same every time the code is run, I have set a random seed using <strong><em>torch.manual_seed().</em></strong></p><p>I have kept the validation set size to be 400 and the training set size as 2925. As, the number of data is really very less, I haven’t created any test set and will be relying on the validation set solely to evaluate my model.</p><h3>Visualizing the data</h3><p>I will now define a helper function that uses the <strong><em>matplotlib.pyplot()</em></strong> method to plot the images.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D3&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D3&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b0116f363b44daa4fb43098c545a80d/href">https://medium.com/media/2b0116f363b44daa4fb43098c545a80d/href</a></iframe><p>Let us now see some of the examples.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D4&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D4&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/ffd93d152319fff4b5f6bf57cfebd8c4/href">https://medium.com/media/ffd93d152319fff4b5f6bf57cfebd8c4/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D5&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D5&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/a454b49126330164bc307bae80a266b4/href">https://medium.com/media/a454b49126330164bc307bae80a266b4/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D6&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D6&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6da23197953adf2a3706a90bc07099a/href">https://medium.com/media/a6da23197953adf2a3706a90bc07099a/href</a></iframe><h3>Creating DataLoaders</h3><p>Now, to ensure that the data is loaded in batches during the training we need to create data loaders for the training and validation sets.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D7&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D7&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/1564c24542da137b64ed6daa0143ba0d/href">https://medium.com/media/1564c24542da137b64ed6daa0143ba0d/href</a></iframe><p>As you can see in the code above that I have set the batch size to be 64. Please read more about the other parameters from the <a href="https://pytorch.org/docs/stable/data.html">documentation</a>.</p><p>Let us see a batch of data.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D8&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D8&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/6553441becdf2b5c7154fcc436a544b5/href">https://medium.com/media/6553441becdf2b5c7154fcc436a544b5/href</a></iframe><h3>Defining the model</h3><p>Let us now define the accuracy method which will help us visualize the accuracy of our model during the training process and we shall also define a helper class that has methods to perform loss calculation during training and validation, loss calculation and prediction generations during validation and printing logs to update us during the training process.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D9&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D9&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/26e6f8cdd0f4702f31290ea0a8f48108/href">https://medium.com/media/26e6f8cdd0f4702f31290ea0a8f48108/href</a></iframe><p>Now, we will define the model and we will inherit the class <strong><em>ColombianHandGestureImageClassificationBase </em></strong>which has all the utilities for training and validation as defined in the code block above.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D10&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D10&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad29a461a05909be9b8da6921c25177a/href">https://medium.com/media/ad29a461a05909be9b8da6921c25177a/href</a></iframe><p>As seen in the code, I have used a <strong><em>resnet50</em></strong> pre-trained model and I have replaced the last layer according to my need to produce 11 outputs as the dataset I have is classified into 11 different hand gestures.</p><p>This method of using a pretrained model to solve your problem by making small changes in the model like changing the last layer in this case is called <strong><em>transfer learning</em></strong>.</p><p>One interesting thing that you can see in the code above are the <strong><em>freeze()</em></strong> and <strong><em>unfreeze()</em></strong> methods.</p><p>I will explain in more details their functionality when I will actually be using them but right now just to give a basic idea, the <strong><em>freeze()</em></strong> method is used to freeze all the layers of the model except the last one so that these layers do not get trained which means that during the training process the weights in these layers shall not change at all. And the opposite of that is the <strong><em>unfreeze()</em></strong> method which is used to ensure that all the layers gets trained, thus, the weights of the layers which has been unfreezed shall now be updated.</p><h3>Helper method to use device dynamically</h3><p>Now, the device on which our model gets trained might be a CPU or a GPU(cuda) and our model shall train on the available device, so the helper function below shall load the model depending on the device available.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D11&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D11&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0000f88ccec3fb5b864213f5210428e/href">https://medium.com/media/c0000f88ccec3fb5b864213f5210428e/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D12&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D12&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/74b56c1146ed8cca6728285c8bc4ecba/href">https://medium.com/media/74b56c1146ed8cca6728285c8bc4ecba/href</a></iframe><p>As you can see that the device available is <strong><em>cuda </em></strong>as I have trained this model on a GPU accelerator in kaggle.</p><p>Let us now load the model onto the GPU.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D14&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D14&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/1054243b7c783414efa03d0f01622374/href">https://medium.com/media/1054243b7c783414efa03d0f01622374/href</a></iframe><h3>Training</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D15&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D15&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a53978ce49110d0055bdaa7723d393f/href">https://medium.com/media/1a53978ce49110d0055bdaa7723d393f/href</a></iframe><p>There are many things going on in the code block above. Let us try to understand what are the things going on.</p><p>Let us start with the <strong><em>evaluate()</em></strong> method. This method is essentially used to perform the validation step. It calls the <strong><em>validation_step() </em></strong>that generates the predictions by the model and also produces the output for the validation data which helps in assessing the model. The annotation <strong><em>@torch.no_grad() </em></strong>is to signify that no gradient calculation will be done when the validation step is in progress.</p><p>Now about the <strong><em>get_lr() </em></strong>method. Before I talk about this method, we first want to know about “<strong><em>learning rate scheduling</em></strong>”. In this method, instead of using a single learning rate, we use different learning rates throughout the training process, we just provide the maximum possible learning rate and then the model starts by using a significantly small learning rate and then gradually increases it to the maximum allowed learning rate and then slowly decreases it significantly. This process of learning rate scheduling is called the “<strong><em>One Cycle Learning Rate Policy</em></strong>” and you can read more on this <a href="https://sgugger.github.io/the-1cycle-policy.html">here</a>.</p><p>So back to this method <strong><em>get_lr(). </em></strong>In the <strong><em>fit_one_cycle() </em></strong>method which is essentially the method used for training we define a variable called <strong><em>sched </em></strong>which is the learning rate scheduler and we use the scheduler provided by torch, so when we do a <strong><em>sched.step() </em></strong>the learning rate takes the next possible value and to observe what value is the current learning rate, we use the <strong><em>get_lr()</em></strong> method.</p><p>So, then its the general training process, where we load in batch and then train followed by validation.</p><p>Let’s start training the model!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D19&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D19&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/916415cbb54d0c9e238a0fabb9d44c4d/href">https://medium.com/media/916415cbb54d0c9e238a0fabb9d44c4d/href</a></iframe><p>We define the hyper-parameters in the code block above.</p><p>We first freeze all the layers other than the final layer by using the <strong><em>model.freeze() </em></strong>method. We do this because as we are using the pre trained model(resnet50) which is already trained to identify objects, we do not want to retrain and adjust the weights.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D18&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D18&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/b59252f3a8cee06af504fde1f20cdbe6/href">https://medium.com/media/b59252f3a8cee06af504fde1f20cdbe6/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D20&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D20&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9b4b659352d990dda356a3b08bb88dd/href">https://medium.com/media/d9b4b659352d990dda356a3b08bb88dd/href</a></iframe><p>After the training is done, we now understand that the model is doing significantly well and so we now want to tune all the layers, so we unfreeze all the layers and perform another round of training.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D21&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D21&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea859ea63d0ea583e5505b4046c51d1c/href">https://medium.com/media/ea859ea63d0ea583e5505b4046c51d1c/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D22&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D22&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/e265a5e2cdc36ad8c13771b33610a5e3/href">https://medium.com/media/e265a5e2cdc36ad8c13771b33610a5e3/href</a></iframe><p>We can observe that we have reached a significant accuracy of 67%.</p><h3>Visualizing the results</h3><p>Let us now plot the accuracies, losses and the learning rates.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D23&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D23&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/8bc75f32e0343f264f70f70f567bdb3a/href">https://medium.com/media/8bc75f32e0343f264f70f70f567bdb3a/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D24&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D24&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7140b707094da8561711c197d83879e/href">https://medium.com/media/d7140b707094da8561711c197d83879e/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D25&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D25&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/c77b111070665af06a6623cca0c5d224/href">https://medium.com/media/c77b111070665af06a6623cca0c5d224/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D26&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D26&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b878b19b633e867c419d7c0f523dc7b/href">https://medium.com/media/7b878b19b633e867c419d7c0f523dc7b/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D27&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D27&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/eabbc28975f09a61aaf32490f97bcf69/href">https://medium.com/media/eabbc28975f09a61aaf32490f97bcf69/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D28&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fcolombian-hand-gesture-recognition%2Fv%2F7%26cellId%3D28&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/99af4d7dcfbc29b2fc6ad283978a6417/href">https://medium.com/media/99af4d7dcfbc29b2fc6ad283978a6417/href</a></iframe><h3>Conclusion</h3><p>So, in this article I have majorly focused on the code and the dataset that I have used and I haven’t delved much into the code. For further understanding of the code do check out this <a href="https://www.youtube.com/watch?v=sJF6PiAjE1M">YouTube video by Jovian.ml</a> where the concepts are thoroughly explained. Also, there are very high level prospects of increasing the accuracy by using different number of epochs, maybe using a different model, maybe by not using transfer learning at all. Please try your hands on and tell me about your findings. Also, do notify me if you see any discrepancies in this article. Appreciate you spending your time to read this article. Thanks !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d830ba7b706e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using CNN to classify daily objects from the CIFAR 10 dataset]]></title>
            <link>https://ai.plainenglish.io/using-cnn-to-classify-daily-objects-from-the-cifar-10-dataset-f27b9d1cd921?source=rss-3c7286668559------2</link>
            <guid isPermaLink="false">https://medium.com/p/f27b9d1cd921</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[convolution-neural-net]]></category>
            <category><![CDATA[regularization]]></category>
            <category><![CDATA[batch-normalization]]></category>
            <category><![CDATA[overfitting]]></category>
            <dc:creator><![CDATA[Attyuttam Saha]]></dc:creator>
            <pubDate>Sun, 02 Aug 2020 20:40:55 GMT</pubDate>
            <atom:updated>2020-08-02T20:40:55.376Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using PyTorch to classify 10 different kinds of objects using simple CNN</h4><p>This will be a simple code walkthrough with basic explanations about most of the code and also a basic discussion on <a href="https://en.wikipedia.org/wiki/Convolutional_neural_network">Convolutional Neural Networks</a> to achieve the target of successfully classifying objects(images) using a <a href="https://en.wikipedia.org/wiki/Convolutional_neural_network">Convolutional Neural Network</a>. I will be using PyTorch to write the code.</p><p>This code has been taken from a tutorial by <a href="https://jovian.ml/forum/c/pytorch-zero-to-gans/18">Jovian.ml</a> on PyTorch and I found it really interesting and wanted to discuss on the same by making a few tweaks, so let’s get started !</p><h3>Importing Libraries</h3><p>I will import all the libraries at once in this code block.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F1%26cellId%3D2&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F1%26cellId%3D2&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ed1fe9f330ebbe0e29ecc2cb8af26ff/href">https://medium.com/media/2ed1fe9f330ebbe0e29ecc2cb8af26ff/href</a></iframe><h3>Downloading the dataset</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F1%26cellId%3D4&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F1%26cellId%3D4&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f36a2096496a1d887f95f480a4521a2/href">https://medium.com/media/4f36a2096496a1d887f95f480a4521a2/href</a></iframe><p>As you can see the code block above, I am downloading the cifar10 dataset from <a href="http://files.fast.ai/data/cifar10.tgz">fast.ai</a> and to perform the download I am using <strong>download_url </strong>from <strong>torchvision.datasets.utils </strong>which essentially allows us to download data from the url and place it in the root. You can read more about this utility function from <a href="https://www.kite.com/python/docs/torchvision.datasets.utils.download_url">here</a>.</p><h3>Extracting data from the downloaded tar file</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F1%26cellId%3D5&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F1%26cellId%3D5&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/3301e450104c1fc3a4d22120497189e1/href">https://medium.com/media/3301e450104c1fc3a4d22120497189e1/href</a></iframe><p>Using the python library <strong>tarfile, </strong>I now extract the data from the tar file that I just downloaded and place the data in a folder called ‘data’ in root. You can read more about <strong>tarfile</strong> in <a href="https://docs.python.org/3/library/tarfile.html">here</a>.</p><h3>Exploring the data</h3><p>I will now just take a simple look into the data that just got downloaded and extracted.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F1%26cellId%3D7&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F1%26cellId%3D7&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/68518c158576fbd72b5ae8d0d3d2ada3/href">https://medium.com/media/68518c158576fbd72b5ae8d0d3d2ada3/href</a></iframe><p>In the code snippet above, I first try to see what’s there in the cifar10 directory under data directory and as we can see that there is a text file named ‘labels.txt’ and two folders ‘test’ and ‘train’. We will now see further that both test and train contains 10 different folders where each folder contains images of a particular kind of object.</p><p>As we can see in the code snippet above, I have listed down the contents of the train folder and all the directories inside it have been listed down in the output some of which are airplane, automobile, bird etc.</p><p>One more thing you should notice that we are using the <strong>listdir </strong>function from the <strong>os </strong>library which helps us in performing basic utilities like listing down contents of a folder as we are doing here. You can read more about it <a href="https://docs.python.org/3/library/os.html">here</a>.</p><p>Now, it will be wise to spend some time to look into at least one of the directories containing the images of the objects.</p><p>Let’s start by looking into the airplane folder under the train folder.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F1%26cellId%3D9&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F1%26cellId%3D9&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ffc2b7c4af397268c0434f931340c7a/href">https://medium.com/media/2ffc2b7c4af397268c0434f931340c7a/href</a></iframe><p>As we can see that the number of images for training of an airplane is 5000, similarly all the other object folders in the train folder contains 5000 images each.</p><p>Now, let’s also have a look inside the ship folder inside the test folder.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F1%26cellId%3D10&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F1%26cellId%3D10&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/d81f28ed9e41336012cdd0f5ea9bd8c7/href">https://medium.com/media/d81f28ed9e41336012cdd0f5ea9bd8c7/href</a></iframe><p>As we can see that there are a 1000 images for testing a ship. All the other object folders under test contains 1000 images each.</p><h3>Creating the dataset</h3><p>Now, we will be using the <strong>ImageFolder</strong> library to convert all the test images into tensors. You can read more about <strong>ImageFolder</strong> <a href="https://pytorch.org/docs/stable/torchvision/datasets.html#imagefolder">here</a>. We will be using the <strong>transform</strong> parameter to convert the images into tensors by setting the value of this parameter to <strong>ToTensor()</strong>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F1%26cellId%3D11&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F1%26cellId%3D11&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf30593d3dea732027d3644f7a03487b/href">https://medium.com/media/cf30593d3dea732027d3644f7a03487b/href</a></iframe><p>Now, let us look at one of the elements of the dataset.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F1%26cellId%3D13&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F1%26cellId%3D13&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/834235fdbfadaad8690c9a3efc52d1c9/href">https://medium.com/media/834235fdbfadaad8690c9a3efc52d1c9/href</a></iframe><p>So, each element has an image tensor (<strong>img) </strong>and a <strong>label. </strong>The image tensor has a shape of (3, 32, 32) as it has 3 channels since its a color image so the 3 channels are Red, Green and Blue. Also, the size of image is 32x32 pixels, hence, the two other elements are 32.</p><p>The label represents the kind of object that the image represents. The labels range from 0 to 9 to represent each of the 10 objects in the cifar10 dataset. The classes can be seen using the <strong>.classes</strong> property of the dataset. We can find out which label represents which class by the index of the class of objects as shown below.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F1%26cellId%3D15&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F1%26cellId%3D15&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/20eb85a5dccc3656c98de62e3e27cca6/href">https://medium.com/media/20eb85a5dccc3656c98de62e3e27cca6/href</a></iframe><p>So, 0 represents an airplane.</p><h3>Viewing the images</h3><p>We will now be using the <strong>matplotlib</strong> library to view the images. Now, the <strong>plt.imshow() </strong>method that we will be using to plot the images takes the channel as the last dimension unlike in the original image where the first dimension represents the number of channels. So, to do that we use the <strong>permute</strong> property of the image. We achieve all this by creating the helper function as show below.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F1%26cellId%3D17&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F1%26cellId%3D17&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/bba4c684483a25ea69974a13ac85a33c/href">https://medium.com/media/bba4c684483a25ea69974a13ac85a33c/href</a></iframe><p>Let us have a look into few of the images.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F1%26cellId%3D19&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F1%26cellId%3D19&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/49939c1f5a6a8cd77ea404b0a8f21610/href">https://medium.com/media/49939c1f5a6a8cd77ea404b0a8f21610/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D20&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D20&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/37b006da1b716b585c12e0633217d251/href">https://medium.com/media/37b006da1b716b585c12e0633217d251/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D21&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D21&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/9dffc08320f63446f8cbafd5d05a5cbe/href">https://medium.com/media/9dffc08320f63446f8cbafd5d05a5cbe/href</a></iframe><p>As we can see that the images are of so poor quality that recognizing them is pretty difficult even for the human eye.</p><h3>Training and Validation Datasets</h3><p>We generally segregate our set of images into 3 parts: training, validation and test datasets.</p><p>The training dataset is used for training the model that will be used for classification. This set will be used to update the parameters and for computing loss.</p><p>The validation set is used to determine whether the model is learning properly or not during the training process and it is used generally to adjust the hyperparameters.</p><p>The test set is used to determine the final accuracy of the model.</p><p>We already have a test dataset provided by the cifar10 dataset itself but there’s no validation set, so I randomly select 5000 images from the training dataset as validation images. You can select any number as you want but do keep in mind that you will be needing a good number of images for training.</p><p>I will be using the <strong>random_split </strong>method from PyTorch to perform the random split and to ensure that each time we do a random split, we get the same split we set a random seed for the random number generator.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D24&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D24&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2e50914696ec44911ebd753f1246077/href">https://medium.com/media/f2e50914696ec44911ebd753f1246077/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D25&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D25&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/aefa748634930da8ddeb74227b969426/href">https://medium.com/media/aefa748634930da8ddeb74227b969426/href</a></iframe><p>We will now use <strong>DataLoader </strong>to create data loaders for training and validation which shall help to load the data in batches. You can read more about <strong>DataLoader</strong> <a href="https://pytorch.org/docs/stable/data.html">here</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D27&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D27&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5d970770357a46d3c081e8092f8cb4a/href">https://medium.com/media/a5d970770357a46d3c081e8092f8cb4a/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D28&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D28&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b7ec08a90d3efceafc1bb2e14ebeba6/href">https://medium.com/media/2b7ec08a90d3efceafc1bb2e14ebeba6/href</a></iframe><p>Below I have added just a helper function to see a random set of images in batches. It is not necessary for you to understand this piece of code as it shall in no way help you to understand the classification process, so I will skip the explanation.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D30&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D30&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/b366b40620bc6b7f6e4e674f2d596ae1/href">https://medium.com/media/b366b40620bc6b7f6e4e674f2d596ae1/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D31&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D31&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ff057f74dc8667d16d69914ea21b7c5/href">https://medium.com/media/8ff057f74dc8667d16d69914ea21b7c5/href</a></iframe><h3>Defining the Model(Convolutional Neural Network)</h3><p>To implement a CNN, I will be using the <strong>nn.conv2d</strong> class from PyTorch.</p><p>According to Wikipedia:</p><blockquote>The name “convolutional neural network” indicates that the network employs a mathematical operation called <a href="https://en.wikipedia.org/wiki/Convolution">convolution</a>. Convolution is a specialized kind of linear operation. Convolutional networks are simply neural networks that use convolution in place of general matrix multiplication in at least one of their layers.”</blockquote><p>You can read more about CNNs from <a href="https://en.wikipedia.org/wiki/Convolutional_neural_network#">Wikipedia </a>and <a href="https://towardsdatascience.com/a-comprehensive-guide-to-convolutional-neural-networks-the-eli5-way-3bd2b1164a53">this great article</a> on towardsdatascience.</p><p>So essentially a <strong>kernel </strong>is used which is nothing but a small matrix maybe a 3x3 matrix or more and comprises of weights. This kernel is moved over the original matrix and an element wise multiplication is performed upon the part of the input matrix on which the kernel is being applied and the result of the element wise multiplication is summed up and put into a single cell. The animation below can provide you a better view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/0*ILSuYAHAbo7rEyAh.gif" /><figcaption>A standard convolution operation. Source: <a href="https://towardsdatascience.com/intuitively-understanding-convolutions-for-deep-learning-1f6f42faee1">Intuitively Understanding Convolutions for Deep Learning</a> by <a href="https://towardsdatascience.com/@irhumshafkat">Irhum Shafkat</a></figcaption></figure><p>It will be wise to talk a bit about Max Pooling too right now as we will also be using that in our model. This is used to gradually reduce the height and width of the input when passed through the convolutional layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*KrUb-FEc5FRuqZyp.png" /><figcaption>A Max pooling operation. Source: <a href="https://computersciencewiki.org/index.php/Max-pooling_/_Pooling">Computer Science Wiki</a></figcaption></figure><p>We will be using <strong>nn.MaxPool2d </strong>which is a class from PyTorch to add the max pooling layer in our model.</p><p>The Convolution layer transforms the 3-channel dimension into a 16-channel feature map and the Max pooling layer cuts down the height and width into half. The feature map gets smaller as we pass the input data through the layers and finally we are left with a feature map which can be flattened into a vector. After that we add a fully connected later to get a vector of size 10 which represents the probability for each of the 10 objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_RXna-hC-hFXvI6A.png" /><figcaption>The entire CNN model. Source: <a href="https://jovian.ml/aakashns/05-cifar10-cnn">Jovian.ml</a></figcaption></figure><p>Before we define the model, we will define a base class which contains a few helper methods for training and validation. The code block below also contains a method for determine the accuracy of the model.</p><p>To know more about the loss functions, the training steps, the device loaders etc, I will suggest you to skim to the parts of <a href="https://medium.com/ai-in-plain-english/comparison-between-logistic-regression-and-neural-networks-in-classifying-digits-dc5e85cd93c3">this article of mine</a> where I have explained the aforementioned topics.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D35&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D35&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/285e89efe99fdf60126c497f2623488b/href">https://medium.com/media/285e89efe99fdf60126c497f2623488b/href</a></iframe><p>We will use <strong>nn.Sequential </strong>from PyTorch to put all these layers of convolution and max pooling in a sequence that we want.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D37&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D37&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/e07a393ff55f7212b29e030ae1f8ca29/href">https://medium.com/media/e07a393ff55f7212b29e030ae1f8ca29/href</a></iframe><h3>Wrapping the model in a CPU/GPU</h3><p>I have also written a few helper functions and a helper class to move the model to the GPU or CPU as when one is available. These helper class and functions is necessary because as our models grow and become complicated, it ends up taking more time and power to train and having a GPU do all these tasks makes the process much faster. GPUs contain a lot more cores compared to CPUs and as these cores are optimized to obtain maximum performance. As GPUs are so effective they are capable of performing expensive matrix operations on floating point number in a very short time which makes them a suitable candidate for training Deep Neural Networks with many layers. You can use GPUs for free on <a href="https://www.kaggle.com/kernels">Kaggle kernels</a> or <a href="https://colab.research.google.com/notebooks/intro.ipynb">Google Colab</a>, or rent GPU-powered machines on services like <a href="https://cloud.google.com/gpu/">Google Cloud Platform</a>, <a href="https://docs.aws.amazon.com/dlami/latest/devguide/gpu.html">Amazon Web Services</a> or <a href="https://www.paperspace.com/">Paperspace</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D42&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D42&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/660118fbc72992258a3043b42bbcd89c/href">https://medium.com/media/660118fbc72992258a3043b42bbcd89c/href</a></iframe><p>Let us have a brief look into the helper methods.</p><p>the <strong>get_default_device() </strong>method uses the <strong>torch.cuda.is_available() </strong>method to check whether the necessary NVIDIA CUDA drivers and of course whether the GPU is present or not.</p><p>The <strong>to_device() </strong>method is used to move the data and model to the chosen device.</p><p>The <strong>DeviceDataLoader() </strong>class is used to invoke the <strong>to_device()</strong> method and move the data and model to the chosen device, so let us see how we use the <strong>DeviceDataLoader</strong> class to load our model and data to the device (GPU/CPU).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D44&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D44&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/83366a52d1e43ce91da056955ab71eea/href">https://medium.com/media/83366a52d1e43ce91da056955ab71eea/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D46&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D46&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/31bc0b433b33c29c69817df57a3e9935/href">https://medium.com/media/31bc0b433b33c29c69817df57a3e9935/href</a></iframe><h3>Training the model</h3><p>There are two functions that I have defined for training the model. The <strong>evaluate()</strong> method is to evaluate the model i.e perform the validation step and the <strong>fit()</strong> method performs the training and adjusts the weights accordingly. For more description on the steps, have a look into <a href="https://medium.com/ai-in-plain-english/comparison-between-logistic-regression-and-neural-networks-in-classifying-digits-dc5e85cd93c3">this article</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D48&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D48&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/c021eeeb26a478e24951b2b1a50641f6/href">https://medium.com/media/c021eeeb26a478e24951b2b1a50641f6/href</a></iframe><p>Now the training methods are ready, let us start training the model !</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D53&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D53&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/781da7dcddf33da8502a1561ee796e52/href">https://medium.com/media/781da7dcddf33da8502a1561ee796e52/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D54&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D54&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5b29cedae1fcfc08c8cd7c4807e62c5/href">https://medium.com/media/f5b29cedae1fcfc08c8cd7c4807e62c5/href</a></iframe><p>We set the hyperparameters(number of epochs as 10 , learning rate as 0.001 and the optimizer as the<strong> Adam optimizer</strong>) and then we start training by calling the <strong>fit()</strong> method with these hyperparameters.</p><p>Let us also plot the accuracies that we have achieved during the training process.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D56&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D56&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c3b346833c5f1d749204267c1905597/href">https://medium.com/media/5c3b346833c5f1d749204267c1905597/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D57&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D57&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/55953f9db3cc675da29775c49ddb3ea3/href">https://medium.com/media/55953f9db3cc675da29775c49ddb3ea3/href</a></iframe><p>The accuracy achieved is around 76% as we can see from the logs. If we observe the graph it seems that the graph has started to flatten out at around 76% and thus it can be inferred that by using this model it won’t be possible to achieve an accuracy higher than or close to 80% even if we train for a long time or change the hyperparameters. To improve the accuracy further, we need a more powerful model and that can be achieved by adding more convolutional layers to our model or by adding regularization techniques etc.</p><h3>Understanding Over-fitting</h3><p>According to Wikipedia,</p><blockquote>In statistics, <strong>overfitting</strong> is “the production of an analysis that corresponds too closely or exactly to a particular set of data, and may therefore fail to fit additional data or predict future observations reliably”</blockquote><p>Essentially, if your model does way too well with the training data but fails to perform good with the test/validation dataset, we can say that we have overfitted the model to the training data.</p><p>Let us plot the curve for the losses encountered with the training data and the validation data.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D59&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D59&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/1096fec8e01b4c01cfa904c6b908f3b4/href">https://medium.com/media/1096fec8e01b4c01cfa904c6b908f3b4/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D60&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D60&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/8686237687d9878878b41cf0b44876b8/href">https://medium.com/media/8686237687d9878878b41cf0b44876b8/href</a></iframe><p>We can observe that initially the losses of training as well as validation seems to decrease but after a certain point of time, although the loss of the training dataset keeps on decreasing but the loss of the validation set has started to increase. That is the point where we can state that the model has started to overfit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*_AS5WvLXCVM3u-W9.jpg" /><figcaption>Overfitting. Image source: <a href="https://elitedatascience.com/overfitting-in-machine-learning">Elite Data Science</a></figcaption></figure><h4><strong>Why does overfitting happen ?</strong></h4><p>Well during the process of training, in an attempt to reduce the loss of the model, the model starts to fit itself to the unique patterns of the training dataset thereby reducing the loss it encounters by making more accurate predictions but as those patterns that it has learnt is specific to the training dataset, it performs poorly in the test dataset as those patterns might be absent in the unknown test set.</p><p>Thus, in an attempt to reduce loss when the model ends up learning specific patterns or memorizing the training dataset, it ends up over-fitting the training dataset and that makes it a poor performer when used in real world unknown test cases.</p><p>There are many ways we can reduce this overfitting such as by stopping the training early as mentioned in the image above, getting more training examples so that there is no specific unique pattern or by using <a href="https://medium.com/ai-quest/regularization-techniques-a-list-down-70df0e8693c">regularization techniques</a>.</p><p>In this article, I will not focus on overfitting as I solely want to focus on CNNs and their usage. There will be more articles soon where I will demonstrate overfitting.</p><h3>Testing</h3><p>Let us now use our model to predict images from the test dataset.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D63&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D63&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/09c9cf1bcf4dcf325772a9c5508b4366/href">https://medium.com/media/09c9cf1bcf4dcf325772a9c5508b4366/href</a></iframe><p>I will define a helper function which when called with the image shall produce the predicted label by the model.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D65&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D65&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ec79261589f86622c233e094234cf63/href">https://medium.com/media/5ec79261589f86622c233e094234cf63/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D66&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D66&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe14e6f1e76531bd1a250bbe264f94e1/href">https://medium.com/media/fe14e6f1e76531bd1a250bbe264f94e1/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D67&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D67&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8b8553f7492db8c20d7afa78ae6db7d/href">https://medium.com/media/e8b8553f7492db8c20d7afa78ae6db7d/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D68&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fclassifying-daily-objects-cnn%2Fv%2F2%26cellId%3D68&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ac5a839e7c14619b17ebf0b7fd71aed/href">https://medium.com/media/4ac5a839e7c14619b17ebf0b7fd71aed/href</a></iframe><h3>Conclusion</h3><p>Thus, we can see that our model does fairly well but as it has a 70% accuracy, it will not do that well and we can improve that by various techniques. Feel free to change the hyperparameters, maybe add more layers to the CNN, change the optimizer function or the activation function and play around with the model and maybe increase its accuracy in the process.</p><p>I am new to writing articles in medium and it has really been fun because of the support I have received and the enjoyment I get in expressing my thoughts about the concepts I have learnt to the world. Please feel free to drop your comments so that I can write and learn better! Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f27b9d1cd921" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/using-cnn-to-classify-daily-objects-from-the-cifar-10-dataset-f27b9d1cd921">Using CNN to classify daily objects from the CIFAR 10 dataset</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comparison between Logistic Regression and Neural networks in classifying digits]]></title>
            <link>https://ai.plainenglish.io/comparison-between-logistic-regression-and-neural-networks-in-classifying-digits-dc5e85cd93c3?source=rss-3c7286668559------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc5e85cd93c3</guid>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[classification-algorithms]]></category>
            <category><![CDATA[artificial-neural-network]]></category>
            <dc:creator><![CDATA[Attyuttam Saha]]></dc:creator>
            <pubDate>Sun, 12 Jul 2020 06:42:50 GMT</pubDate>
            <atom:updated>2020-07-20T22:01:59.828Z</atom:updated>
            <content:encoded><![CDATA[<h4>Detailed comparison including an explanation of the code</h4><p>I recently learned about logistic regression and feed forward neural networks and how either of them can be used for classification. What bugged me was what was the difference and why and when do we prefer one over the other. So, I decided to do a comparison between the two techniques of classification theoretically as well as by trying to solve the problem of classifying digits from the MNIST dataset using both the methods. In this article, I will try to present this comparison and I hope this might be useful for people trying their hands in Machine Learning.</p><h3>Source</h3><p>The code that I will be using in this article are the ones used in the tutorials by Jovian.ml and <a href="https://medium.com/u/8b318225c16a">freeCodeCamp</a> on YouTube. The link has been provided in the references below.</p><h3>Problem Statement</h3><p><em>Given a handwritten digit, the model should be able to tell whether the digit is a 0,1,2,3,4,5,6,7,8 or 9.</em></p><p>We will use the MNIST database which provides a large database of handwritten digits to train and test our model and eventually our model will be able to classify any handwritten digit as 0,1,2,3,4,5,6,7,8 or 9. It consists of 28px by 28px grayscale images of handwritten digits (0 to 9), along with labels for each image indicating which digit it represents. We will learn how to use this dataset, fetch all the data once we look at the code.</p><p>Let us have a look at a few samples from the MNIST dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/0*6tyGak8zEvkU53jB.jpg" /><figcaption>Examples of handwritten digits from the MNIST dataset</figcaption></figure><p>Now that we have a clear idea about the problem statement and the data-source we are going to use, let’s look at the fundamental concepts using which we will attempt to classify the digits.</p><p><em>You can ignore these basics and jump straight to the code if you are already aware of the fundamentals of logistic regression and feed forward neural networks.</em></p><h3>Logistic Regression</h3><p>I will not talk about the math at all, you can have a look at the <a href="https://en.wikipedia.org/wiki/Logistic_regression">explanation of Logistic Regression provided by Wikipedia</a> to get the essence of the mathematics behind it.</p><p>So, Logistic Regression is basically used for classifying objects. It predicts the probability(<strong><em>P(Y=1|X)</em></strong>) of the target variable based on a set of parameters that has been provided to it as input. For example, say you need to say whether an image is of a cat or a dog, then if we model the Logistic Regression to produce the probability of the image being a cat, then if the output provided by the Logistic Regression is close to 1 then essentially it means that Logistic Regression is telling that the image that has been provided to it is that of a cat and if the result is closer to 0, then the prediction is that of a dog.</p><p>It is called Logistic Regression because it used the logistic function which is basically a sigmoid function. A sigmoid function takes in a value and produces a value between 0 and 1. Why is this useful ? Because probabilities lie within 0 to 1, hence sigmoid function helps us in producing a probability of the target value for a given input.</p><p>The sigmoid/logistic function looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*6Cyskdc9sGcH7mECu2TxOw.png" /><figcaption>Source: <a href="https://en.wikipedia.org/wiki/Logistic_regression">Wikipidea</a></figcaption></figure><p>where <strong><em>e</em></strong> is the exponent and <strong><em>t </em></strong>is the input value to the exponent.</p><p>Generally <strong><em>t </em></strong>is a linear combination of many variables and can be represented as :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*Bk7H5DI8-vZv5C5lRcqruQ.png" /></figure><p>The standard logistic function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*md8FAy2T2u1ssq_E.png" /><figcaption>The standard logistic function {σ (t)}; note that σ (t)∈ (0,1) for all t (Source: Wikipedia)</figcaption></figure><p><strong>NOTE:</strong> Logistic Regression is simply a linear method where the predictions produced are passed through the non-linear sigmoid function which essentially renders the predictions independent of the linear combination of inputs.</p><h3>Neural networks</h3><p>Artificial Neural Networks are essentially the mimic of the actual neural networks which drive every living organism. They are currently being used for variety of purposes like classification, prediction etc. In Machine Learning terms, why do we have such a craze for Neural Networks ? Because they can approximate any complex function and the proof to this is provided by the <a href="https://en.wikipedia.org/wiki/Universal_approximation_theorem">Universal Approximation Theorem</a>.</p><p>What does a neural network look like ? Like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/0*Q8uMBg7dW4WF61Kc.png" /><figcaption>ANN with 1 hidden layer, each circle is a neuron. Source: Wikipedia</figcaption></figure><p>That picture you see above, we will essentially be implementing that soon. Now, what you see in that image is called a neural network architecture, you can make your own architecture by defining more than one hidden layers, add more number of neurons to the hidden layers etc. Now, there are some different kind of architectures of neural networks currently being used by researchers like <a href="https://en.wikipedia.org/wiki/Feedforward_neural_network">Feed Forward Neural Networks</a>, <a href="https://en.wikipedia.org/wiki/Convolutional_neural_network">Convolutional Neural Networks</a>, <a href="https://en.wikipedia.org/wiki/Recurrent_neural_network">Recurrent Neural Networks</a> etc.</p><p>In this article we will be using the Feed Forward Neural Network as its simple to understand for people like me who are just getting into the field of machine learning.</p><h3>Feed Forward Neural Networks</h3><p>Let us talk about <a href="https://en.wikipedia.org/wiki/Perceptron">perceptron </a>a bit. This is a neural network unit created by Frank Rosenblatt in 1957 which can tell you to which class an input belongs to. It is a type of <a href="https://en.wikipedia.org/wiki/Linear_classifier">linear classifier</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*ery5YQSsMNxroZTC" /></figure><p><strong>What do you mean by linearly separable data ?</strong></p><p>As you can see in i<strong>mage A</strong> that with one single line( which can be represented by a linear equation) we can separate the blue and green dots, hence this data is called linearly classifiable.</p><p><strong>And what does a non-linearly separable data look like ?</strong></p><p>Like the one in <strong>image B. </strong>We can see that the red and green dots cannot be separated by a single line but a function representing a circle is needed to separate them. As the separation cannot be done by a linear function, this is a non-linearly separable data.</p><p><strong>Why do we need to know about linear/non-linear separable data ?</strong></p><p>Because a single perceptron which looks like the diagram below is only capable of classifying linearly separable data, so we need feed forward networks which is also known as the multi-layer perceptron and is capable of learning non-linear functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/0*SkIQFNHVwqu3RCwd.png" /><figcaption>A single layer perceptron. Source: <a href="https://missinglink.ai/guides/neural-network-concepts/perceptrons-and-multi-layer-perceptrons-the-artificial-neuron-at-the-core-of-deep-learning/">missinglink.ai</a></figcaption></figure><p>A Feed forward neural network/ multi layer perceptron:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/0*qqNA4eDDaTqDRvDc.png" /><figcaption>A multi layer perceptron(Feed Forward Neural Network). Source: <a href="https://missinglink.ai/guides/neural-network-concepts/perceptrons-and-multi-layer-perceptrons-the-artificial-neuron-at-the-core-of-deep-learning/">missinglink.ai</a></figcaption></figure><p><strong>I get all of this, but how does the network learn to classify ?</strong></p><p>Well we must be thinking of this now, so how these networks learn comes from the perceptron learning rule which states that a perceptron will learn the relation between the input parameters and the target variable by playing around (adjusting ) the weights which is associated with each input. If the weighted sum of the inputs crosses a particular thereshold which is custom, then the neuron produces a true else it produces a false value. Now, when we combine a number of perceptrons thereby forming the Feed forward neural network, then each neuron produces a value and all perceptrons together are able to produce an output used for classification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/0*x25UUrrFi5KgIPhC.jpg" /><figcaption>Source: <a href="https://www.simplilearn.com/">Simplilearn</a></figcaption></figure><p>Now that was a lot of theory and concepts !</p><p>I have tried to shorten and simplify the most fundamental concepts, if you are still unclear, that’s perfectly fine. I am sure your doubts will get answered once we start the code walk-through as looking at each of these concepts in action shall help you to understand what’s really going on. I have also provided the references which have helped me understand the concepts to write this article, please go through them for further understanding.</p><p>Let’s start the most interesting part, the code walk-through!</p><h3>Importing Libraries</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F1%26cellId%3D5&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F1%26cellId%3D5&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/af98e6eefa5cd302f33922068b706dfa/href">https://medium.com/media/af98e6eefa5cd302f33922068b706dfa/href</a></iframe><p>We will be working with the MNIST dataset for this article. <em>torchvision</em> library provides a number of utilities for playing around with image data and we will be using some of them as we go along in our code.</p><h3><strong>Downloading the dataset</strong></h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F1%26cellId%3D6&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F1%26cellId%3D6&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/7dd02d3e5d034d25ab9e71317e4ba26c/href">https://medium.com/media/7dd02d3e5d034d25ab9e71317e4ba26c/href</a></iframe><p>As all the necessary libraries have been imported, we will start by downloading the dataset. The code above downloads a PyTorch dataset into the directory <em>data.</em></p><h3>Exploring the data</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F1%26cellId%3D8&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F1%26cellId%3D8&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/896dc78a0a3e8c3a4f15b308395ce494/href">https://medium.com/media/896dc78a0a3e8c3a4f15b308395ce494/href</a></iframe><p>Let us look at the length of the dataset that we just downloaded. We can see that there are 60,000 images in the MNIST training dataset and we will be using these images for training and validation of the model.</p><p>Also, apart from the 60,000 training images, the MNIST dataset also provides an additional 10,000 images for testing purposes and these 10,000 images can be obtained by setting the <em>train</em> parameter as false when downloading the dataset using the MNIST class.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F1%26cellId%3D10&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F1%26cellId%3D10&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/b126854dfce5af5c809e8b4fe9e10c73/href">https://medium.com/media/b126854dfce5af5c809e8b4fe9e10c73/href</a></iframe><p>Each of the elements in the dataset contains a pair, where the first element is the 28x28 image which is an object of the <em>PIL.Image.Image </em>class, which is a part of the Python imaging library Pillow.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F1%26cellId%3D12&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F1%26cellId%3D12&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/63691a74dae4cca9b0708f9e4a6f0149/href">https://medium.com/media/63691a74dae4cca9b0708f9e4a6f0149/href</a></iframe><p>To view the images, we need to import the <em>matplotlib </em>library which is the most commonly used library for plotting graphs while working with machine learning or data science.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F1%26cellId%3D14&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F1%26cellId%3D14&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b899a3cd8b50e2d341a7634b86bbdae/href">https://medium.com/media/1b899a3cd8b50e2d341a7634b86bbdae/href</a></iframe><p>Let us now view the dataset and we shall also see a few of the images in the dataset.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F1%26cellId%3D16&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F1%26cellId%3D16&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2b631c313167dff7d9e06b05c0a3448/href">https://medium.com/media/d2b631c313167dff7d9e06b05c0a3448/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F1%26cellId%3D17&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F1%26cellId%3D17&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/61f0b2ecbaf8ec64784b645ec3e03c22/href">https://medium.com/media/61f0b2ecbaf8ec64784b645ec3e03c22/href</a></iframe><h3>Transforming the data</h3><p>All images are now loaded but unfortunately PyTorch cannot handle images, hence we need to convert these images into PyTorch tensors and we achieve this by using the <em>ToTensor</em> transform method of the <em>torchvision.transforms </em>library.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F1%26cellId%3D19&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F1%26cellId%3D19&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e7943ea6791b520ed2b042b60725e49/href">https://medium.com/media/0e7943ea6791b520ed2b042b60725e49/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F1%26cellId%3D21&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F1%26cellId%3D21&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/9168c4d2272a664c5b0d3bdf68abe0a8/href">https://medium.com/media/9168c4d2272a664c5b0d3bdf68abe0a8/href</a></iframe><p>As we can see in the code snippet above, we have used the MNIST class to get the dataset and then using the <em>transform</em> parameter we have ensured that the dataset is now a PyTorch tensor. We can also observe that there is no <em>download</em> parameter now as we have already downloaded the datset.</p><p>After this transformation, the image is now converted to a 1x28x28 tensor. So, 1x28x28 represents a 3 dimensional vector where the first dimension represents the number of channels in the image, in our case as the image is a grayscale image, hence there’s only one channel but if the image is a colored one then there shall be three channels (Red, Green and Blue).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F1%26cellId%3D22&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F1%26cellId%3D22&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/4fb78c166aee02f062c6b0d7fbbbf139/href">https://medium.com/media/4fb78c166aee02f062c6b0d7fbbbf139/href</a></iframe><p>The values of the <em>img_tensor</em> range from 0 to 1, with 0 representing black, 1 white and the values in between different shades of gray.</p><h3><strong>Creating the Training and Validation Datasets</strong></h3><p>So, we have got the training data as well as the test data. In real world whenever we are training machine learning models, to ensure that the training process is going on properly and there are no discrepancies like <a href="https://en.wikipedia.org/wiki/Overfitting">over-fitting</a> etc we also need to create a validation set which will be used for adjusting hyper-parameters etc. In the training set that we have, there are 60,000 images and we will randomly select 10,000 images from that to form the validation set, we will use <em>random_split</em> method for this.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F1%26cellId%3D29&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F1%26cellId%3D29&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f77e33fdbc478758a33796897d364f0/href">https://medium.com/media/5f77e33fdbc478758a33796897d364f0/href</a></iframe><p>We do the splitting randomly because that ensures that the validation images does not have images only for a few digits as the 60,000 images are stacked in increasing order of the numbers like <em>n1</em> images of 0, followed by <em>n2</em> images of 1 …… <em>n10</em> images of 9 where <em>n1</em>+<em>n2</em>+<em>n3</em>+…+<em>n10</em> = 60,000.</p><p>We can now create data loaders to help us load the data in batches. We’ll use a batch size of 128.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F1%26cellId%3D31&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F1%26cellId%3D31&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fe4c9755bdcc94c8eb217293edf8928/href">https://medium.com/media/3fe4c9755bdcc94c8eb217293edf8928/href</a></iframe><p>I will not be going into DataLoader in depth as my main focus is to talk about the difference of performance of Logistic Regression and Neural networks but for a general overview, DataLoader is essential for splitting the data, shuffling and also to ensure that data is loaded into batches of pre-defined size during each epoch in training.</p><h3>Cost Function for Logistic Regression model</h3><p>We are done with preparing the dataset and have also explored the kind of data that we are going to deal with, so firstly, I will start by talking about the cost function we will be using for Logistic Regression.</p><ul><li>A logistic regression model as we had explained above is simply a sigmoid function which takes in any linear function of an <a href="https://en.wikipedia.org/wiki/Dependent_and_independent_variables">explanatory variable</a>.</li><li>Now, logistic regression is essentially used for binary classification that is predicting whether something is true or not, for example, whether the given picture is a cat or dog. This kind of logistic regression is also called Binomial Logistic Regression. But, in our problem, we are going to work on classifying a given handwritten digit image into one of the 10 classes (0–9). <strong>So, the problem we are dealing with is essentially a Multi-class classification and to solve this we will be using the <em>Multinomial Logistic Regression</em> which is also known as <em>Softmax Regression</em>.</strong></li><li>Softmax regression (or multinomial logistic regression) is a generalized version of logistic regression and is capable of handling multiple classes and instead of the sigmoid function, it uses the softmax function. <a href="http://deeplearning.stanford.edu/tutorial/supervised/SoftmaxRegression/">The Stanford notes on Softmax regression</a> explains this in great detail.</li></ul><p>The Softmax function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*b4a9C4ZSPdICKRxv2h-_ng.png" /><figcaption>Source: <a href="http://www.curiousinspiration.com/posts/improving-our-neural-network-outputs-with-softmax-classification">Curious Inspiration</a></figcaption></figure><p>where exp(x) is the exponential of x is the power value of the exponent e.</p><p>I hope we are clear with the importance of using Softmax Regression. Now, we define the model using the nn.Linear class and we feed the inputs to the model after flattening the input image (1x28x28) into a vector of size (28x28). There are 10 outputs to the model each representing one of the 10 digits (0–9).</p><h3>Evaluation Metric and Loss Function</h3><p>To understand whether our model is learning properly or not, we need to define a metric and we can do this by finding the percentage of labels that were predicted correctly by our model during the training process. But, this method is not differentiable, hence the model will not be able to use this to update the weights of the neural network using <a href="https://en.wikipedia.org/wiki/Backpropagation">backpropagation</a>.</p><p>To do that we will use the cross entropy function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*Cmu_mJ778s685zuyDEhmQw.png" /><figcaption>Image from lectures by <a href="https://jovian.ml/forum/c/pytorch-zero-to-gans/18">Jovian.ml</a></figcaption></figure><p>Well in cross entropy, we simply take the probability of the correct label and take the logarithm of the same. The <a href="https://jovian.ml/attyuttam/03-logistic-regression">tutorial on logistic regression by Jovian.ml</a> explains the concept much thoroughly.</p><p>Also, PyTorch provides an efficient and tensor-friendly implementation of cross entropy as part of the <em>torch.nn.functional</em> package. Moreover, it also performs softmax internally, so we can directly pass in the outputs of the model without converting them into probabilities. Hence, we can use the <em>cross_entropy</em> function provided by PyTorch as our loss function.</p><p>For ease of human understanding, we will also define the accuracy method.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F3%26cellId%3D61&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F3%26cellId%3D61&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/285cbf214ccfef34965a67a9bde781b8/href">https://medium.com/media/285cbf214ccfef34965a67a9bde781b8/href</a></iframe><h3>The Logistic Regression Model</h3><p>We have already explained all the components of the model. Here’s the code to creating the model:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F1%26cellId%3D69&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F1%26cellId%3D69&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/209ba3cd0d5b94a8e757e8ef39864ec1/href">https://medium.com/media/209ba3cd0d5b94a8e757e8ef39864ec1/href</a></iframe><p>I have used the Stochastic Gradient Descent as the default optimizer and we will be using the same as the optimizer for the Logistic Regression Model training in this article but feel free to explore and see all the other gradient descent function like Adam Optimizer etc.</p><p>Now, in this model, the training and validation step boiler plate code has also been added, so that this model works as a unit, so to understand all the code in the model implementation, we need to look into the training steps described next.</p><h3>Training and Validation</h3><p>Now that we have defined all the components and have also built the model, let us come to the most awaited, interesting and fun part where the magic really happens and that’s the training part !</p><p>The steps for training can be broken down as:</p><ol><li>Obtain the predictions</li><li>Calculate the loss using the loss function</li><li>Compute gradients w.r.t the weights and biases</li><li>Adjust the weights by subtracting a small quantity proportional to the gradient</li><li>Reset the gradients to zero</li></ol><p>These steps were defined in the <a href="https://www.youtube.com/watch?v=GIsg-ZUy0MY&amp;t=57s">PyTorch lectures by Jovian.ml</a></p><p>Now let us look at the code.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F1%26cellId%3D71&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F1%26cellId%3D71&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c2c6d07861993d21a1e51e152ec395a/href">https://medium.com/media/0c2c6d07861993d21a1e51e152ec395a/href</a></iframe><p>The <em>fit</em> function defined above will perform the entire training process. It records the validation loss and metric from each epoch and returns a history of the training process.</p><p>Also, the <em>evaluate </em>function is responsible for executing the validation phase.</p><p>Let’s start the training process then.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F3%26cellId%3D75&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F3%26cellId%3D75&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/14e3aae3d679081a28c6c0f7668869e4/href">https://medium.com/media/14e3aae3d679081a28c6c0f7668869e4/href</a></iframe><h3>Inference</h3><p>Let us plot the accuracy with respect to the epochs.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F3%26cellId%3D81&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F3%26cellId%3D81&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/eab322662aaa95555d0837907e85c00f/href">https://medium.com/media/eab322662aaa95555d0837907e85c00f/href</a></iframe><p>Our model does fairly well and it starts to flatten out at around 89% but can we do better than this ? The answer to that is yes. Now, we can probably push Logistic Regression model to reach an accuracy of 90% by playing around with the hyper-parameters but that’s it we will still not be able to reach significantly higher percentages, to do that, we need a <strong>more powerful model </strong>as assumptions like the output being a linear function of the input might be preventing the model to learn more about the input-output relationship.</p><h3>Testing</h3><p>Let us now test our model on some random images from the test dataset.</p><p>We will begin by recreating the test dataset with the <em>ToTensor</em> transform.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F2%26cellId%3D87&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F2%26cellId%3D87&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec047824441ead615dd1e1891cb24a4a/href">https://medium.com/media/ec047824441ead615dd1e1891cb24a4a/href</a></iframe><p>Now, let’s define a helper function <em>predict_image</em> which returns the predicted label for a single image tensor.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F2%26cellId%3D92&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F2%26cellId%3D92&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff28e120e4c84be8db0d79f5a0c13feb/href">https://medium.com/media/ff28e120e4c84be8db0d79f5a0c13feb/href</a></iframe><p><em>img.unsqueeze</em> simply adds another dimension at the begining of the 1x28x28 tensor, making it a 1x1x28x28 tensor, which the model views as a batch containing a single image.</p><p>Now, let’s try to predict a few images.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F3%26cellId%3D94&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F3%26cellId%3D94&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/89aade5ed5e0b9b721c950760bca9a9e/href">https://medium.com/media/89aade5ed5e0b9b721c950760bca9a9e/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F3%26cellId%3D95&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F3%26cellId%3D95&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b8676583787291fcba2a62b0b5ac525/href">https://medium.com/media/5b8676583787291fcba2a62b0b5ac525/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F3%26cellId%3D96&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F3%26cellId%3D96&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/798134fb5880ffad91eecebdea9d2daf/href">https://medium.com/media/798134fb5880ffad91eecebdea9d2daf/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F3%26cellId%3D97&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F03-logistic-regression%2Fv%2F3%26cellId%3D97&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb5483f0d8e164a11895e8e09aff9cd8/href">https://medium.com/media/bb5483f0d8e164a11895e8e09aff9cd8/href</a></iframe><p>Thus, we can see that our model does fairly well but when images are a bit complicated, it might fail to predict correctly.</p><p>We will now talk about how to use Artificial Neural Networks to handle the same problem.</p><p>The pre-processing steps like converting images into tensors, defining training and validation steps etc remain the same. But as the model itself changes, hence, so we will directly start by talking about the Artificial Neural Network model.</p><h3>The Artificial Neural Network Model</h3><p>In this article, we will create a simple neural network with just one hidden layer and we will observe that this will provide significant advantage over the results we had achieved using logistic regression.</p><p>In this model we will be using two <em>nn.Linear</em> objects to include the hidden layer of the neural network. The result of the hidden layer is then passed into the activation function, in this case we are using the <a href="https://en.wikipedia.org/wiki/Rectifier_(neural_networks)">ReLu activation function</a> to provide the capability of learning complex non-linear functions to the model.</p><p>Introducing a hidden layer and an activation function allows the model to learn more complex, multi-layered and non-linear relationships between the inputs and the targets. Here’s what the model looks like :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*lxcfJ7Ly3F9U3uzO.png" /><figcaption>Source: Notebook from <a href="https://jovian.ml/forum/c/pytorch-zero-to-gans/18">Jovian.ml</a></figcaption></figure><p>Let us have a look at the code:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F04-feedforward-nn%2Fv%2F1%26cellId%3D16&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F04-feedforward-nn%2Fv%2F1%26cellId%3D16&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/076304b613614abde0f9897a08f2017d/href">https://medium.com/media/076304b613614abde0f9897a08f2017d/href</a></iframe><h3>Training the neural network</h3><p>Training the model is exactly similar to the manner in which we had trained the logistic regression model. Let’s just have a quick glance over the code of the fit and evaluate function:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F04-feedforward-nn%2Fv%2F1%26cellId%3D40&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F04-feedforward-nn%2Fv%2F1%26cellId%3D40&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8683e2c77c0e767cfabad488f1f4679/href">https://medium.com/media/f8683e2c77c0e767cfabad488f1f4679/href</a></iframe><p>Let’s start training!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F04-feedforward-nn%2Fv%2F1%26cellId%3D47&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F04-feedforward-nn%2Fv%2F1%26cellId%3D47&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e54189ffb9d3bb71f786e201bfdfcee/href">https://medium.com/media/7e54189ffb9d3bb71f786e201bfdfcee/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F04-feedforward-nn%2Fv%2F1%26cellId%3D49&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F04-feedforward-nn%2Fv%2F1%26cellId%3D49&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/e919ee73e7fbee2dd8d62df9a4ccf21a/href">https://medium.com/media/e919ee73e7fbee2dd8d62df9a4ccf21a/href</a></iframe><p>We can see from the results that only after 5 epoch of training, we already have achieved 96% accuracy and that is really great. We can increase the accuracy further by using different type of models like CNNs but that is outside the scope of this article.</p><p>Now, let us plot the loss and accuracy.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F04-feedforward-nn%2Fv%2F1%26cellId%3D52&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F04-feedforward-nn%2Fv%2F1%26cellId%3D52&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/c99d62f9727f83e84164e04bd4e913bd/href">https://medium.com/media/c99d62f9727f83e84164e04bd4e913bd/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F04-feedforward-nn%2Fv%2F1%26cellId%3D53&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F04-feedforward-nn%2Fv%2F1%26cellId%3D53&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/102b86028d4336e863fb21df6ccdb9ac/href">https://medium.com/media/102b86028d4336e863fb21df6ccdb9ac/href</a></iframe><h3>Neural network vs Logistic Regression</h3><p>As we had explained earlier, we are aware that the neural network is capable of modelling non-linear and complex relationships. This is because of the activation function used in neural networks generally a sigmoid or relu or tanh etc. Now, how do we tell that just by using the activation function, the neural network performs so marvelously? Well, as said earlier this comes from the <a href="https://en.wikipedia.org/wiki/Universal_approximation_theorem">Universal Approximation Theorem</a> (UAT).</p><p>I will not delve deep into mathematics of the proof of the UAT but let’s have a simple look. The explanation is provided in the <a href="https://towardsdatascience.com/why-are-neural-networks-so-powerful-bc308906696c">medium article by Tivadar Danka</a> and you can delve into the details by going through his awesome article.</p><p>A neural network with only one hidden layer can be defined using the equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*aqT0H7YKsBGC-n1FSXXE8w.png" /></figure><p>and,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*CxgAKW54RiJP5QBUIwCkvA.png" /></figure><p>Don’t get overwhelmed with the equation above, you already have done this in the code above. Go through the code properly and then come back here, that will give you more insight into what’s going on.</p><p>So, in the equation above, φ is a nonlinear function (called activation function) such as the ReLu function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*1qJXtWeTUxib4rLGrwmIyw.png" /></figure><p>or the sigmoid function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*6Cyskdc9sGcH7mECu2TxOw.png" /></figure><p>The above neural network model is definitely capable of any approximating any complex function and the proof to this is provided by the Universal Approximation Theorem which is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*NO95cvN2KCnREWu4BeAvuQ.png" /><figcaption>The Universal Approximation Theorem. Source: Cybenko, G. (1989) <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.441.7873&amp;rep=rep1&amp;type=pdf">“Approximations by superpositions of sigmoidal functions”</a>, Mathematics of Control, Signals, and Systems, 2(4), 303–314.</figcaption></figure><p>Keep calm, if the theorem is too complicated above. It essentially tells that if the activation function that is being used in the neural network is like a sigmoid function and the function that is being approximated is continuous, a neural network consisting of a single hidden layer can approximate/learn it pretty good.</p><p>Thus, neural networks perform a better work at modelling the given images and thereby determining the relationship between a given handwritten digit and its corresponding label.</p><p><strong>So, in practice, one must always try to tackle the given classification problem using a simple algorithm like a logistic regression firstly as neural networks are computationally expensive.</strong></p><h3>Conclusion</h3><p>I am currently learning Machine Learning and this article is one of my findings during the learning process. I read through many articles (the references to which have been provided below) and after developing a fair understanding decided to share it with you all. Please comment if you see any discrepancies or if you have suggestions on what changes are to be done in this article or any other article you want me to write about or anything at all :p . Until then, enjoy reading!</p><h3>Full Code</h3><p>Find the code for Logistic regression <a href="https://jovian.ml/attyuttam/03-logistic-regression">here</a>.</p><p>Find the code for Neural Networks <a href="https://jovian.ml/attyuttam/04-feedforward-nn">here</a>.</p><h3>References</h3><ul><li><a href="https://www.codementor.io/@james_aka_yale/a-gentle-introduction-to-neural-networks-for-machine-learning-hkijvz7lp">https://www.codementor.io/@james_aka_yale/a-gentle-introduction-to-neural-networks-for-machine-learning-hkijvz7lp</a></li><li><a href="https://pytorch.org/docs/stable/index.html">https://pytorch.org/docs/stable/index.html</a></li><li><a href="https://www.simplilearn.com/what-is-perceptron-tutorial">https://www.simplilearn.com/what-is-perceptron-tutorial</a></li><li><a href="https://www.youtube.com/watch?v=GIsg-ZUy0MY">https://www.youtube.com/watch?v=GIsg-ZUy0MY</a></li><li><a href="https://machinelearningmastery.com/logistic-regression-for-machine-learning/">https://machinelearningmastery.com/logistic-regression-for-machine-learning/</a></li><li><a href="http://deeplearning.stanford.edu/tutorial/supervised/SoftmaxRegression">http://deeplearning.stanford.edu/tutorial/supervised/SoftmaxRegression</a></li><li><a href="https://jamesmccaffrey.wordpress.com/2018/07/07/why-a-neural-network-is-always-better-than-logistic-regression">https://jamesmccaffrey.wordpress.com/2018/07/07/why-a-neural-network-is-always-better-than-logistic-regression</a></li><li><a href="https://sebastianraschka.com/faq/docs/logisticregr-neuralnet.html">https://sebastianraschka.com/faq/docs/logisticregr-neuralnet.html</a></li><li><a href="https://towardsdatascience.com/why-are-neural-networks-so-powerful-bc308906696c">https://towardsdatascience.com/why-are-neural-networks-so-powerful-bc308906696c</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc5e85cd93c3" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/comparison-between-logistic-regression-and-neural-networks-in-classifying-digits-dc5e85cd93c3">Comparison between Logistic Regression and Neural networks in classifying digits</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Linear Regression to Predict Max Temperature Based on Weather Conditions]]></title>
            <link>https://medium.com/swlh/using-linear-regression-to-predict-max-temperature-based-on-weather-conditions-2d776947cc2d?source=rss-3c7286668559------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d776947cc2d</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[jovian-ml]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[linear-regression]]></category>
            <dc:creator><![CDATA[Attyuttam Saha]]></dc:creator>
            <pubDate>Sat, 04 Jul 2020 10:52:34 GMT</pubDate>
            <atom:updated>2020-07-13T06:30:02.066Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Is there a relationship between the daily minimum and maximum temperature? Can you predict the maximum temperature given the minimum temperature?</em></p><h3>How I started off</h3><p>I am currently following the free PyTorch series by Jovian.ml and FreeCodeCamp on youtube (Link: <a href="https://www.youtube.com/watch?v=vo_fUOk-IKk&amp;list=PLWKjhJtqVAbm3T2Eq1_KgloC7ogdXxdRa">https://www.youtube.com/watch?v=vo_fUOk-IKk&amp;list=PLWKjhJtqVAbm3T2Eq1_KgloC7ogdXxdRa</a>).</p><p>This is a really interesting series and the mentor, Aaskash has really been doing an excellent job in helping us grow interest in pytorch and Machine Learning.</p><p>This project is part of the assignment provided in part 2 of the tutorial series where we had to work on an unknown dataset and use Linear Regression to perform the operation.</p><h3>The problem statement</h3><p>Dataset link: <a href="https://www.kaggle.com/smid80/weatherww2/data?select=Summary+of+Weather.csv">https://www.kaggle.com/smid80/weatherww2/data?select=Summary+of+Weather.csv</a></p><p>This is a Kaggle problem (link mentioned above) where given a dataset consisting of various parameters of the weather like precipitation level, temperature, snowfall etc, one had to determine what shall be the max temperature of a given day.</p><p>It is a pretty interesting problem to understand linear regression for beginners and I believe I have learnt a lot about linear regression from this project and surely linear regression has done a decent job in determining the relationship between min and max temperatures in any given day.</p><h3>Linear Regression</h3><p>I believe the problem statement is pretty clear now, so I shall start talking about the approach of the solution by giving a brief idea on what is Linear Regression.</p><p>As Wikipedia states:</p><p><em>In statistics, </em><strong><em>linear regression</em></strong><em> is a linear approach to modeling the relationship between a scalar response (or dependent variable) and one or more explanatory variables (or independent variables). The case of one explanatory variable is called </em><strong><em>simple linear regression</em></strong><em>. For more than one explanatory variable, the process is called </em><strong><em>multiple linear regression.</em></strong></p><p>So, linear regression is a mechanism in which we build a linear model which uses one or more than one input parameters(<em>x1, x2, x3..</em>) and uses them to determine an output(<em>y</em>). In mathematical terms, <em>y </em>is a linear combination of the input parameters <em>x1, x2, x3 ..</em></p><p>The form of the model mathematically is:</p><p><strong><em>y = w0 +w1.x1 + w2.x2 + w3.x3 + ….</em></strong></p><p>So, its essentially taking into consideration the effect of each parameter on the output and the effect of each parameter is determined by a coefficient/weight.</p><h3>Solution</h3><p>I will now start with the solution discussion and any concepts that come up, I will try to provide a brief idea on what it is, why do we need it and how are we using it in this scenario. This shall ensure that we learn as we do.</p><p><strong>Step 1: Importing the necessary libraries</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fww2-weather-linear%2Fv%2F1%26cellId%3D3&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fww2-weather-linear%2Fv%2F1%26cellId%3D3&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0d90e8fbcbbf7bd19edad27d2e6b9ad/href">https://medium.com/media/e0d90e8fbcbbf7bd19edad27d2e6b9ad/href</a></iframe><p><strong>Step 2: Reading the dataset into a dataframe</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fww2-weather-linear%2Fv%2F2%26cellId%3D4&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fww2-weather-linear%2Fv%2F2%26cellId%3D4&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4ea8984ed8e6a3fe8d854c7f8855f24/href">https://medium.com/media/c4ea8984ed8e6a3fe8d854c7f8855f24/href</a></iframe><p>In the cell above, I downloaded the dataset “WW2Weather.csv” into the same folder where the ipynb file is located and then I used the read_csv() method from pandas library to read the file into a pandas dataframe.</p><p><strong>Step 3: Understanding the dataset</strong></p><p>The technique of performing linear regression itself does not have much complications, but the real understanding comes up when we try to determine the valid input parameters and the intended output data. For this, we need to understand the dataset.</p><p>In the dataset (<a href="https://www.kaggle.com/smid80/weatherww2/data?select=Summary+of+Weather.csv">https://www.kaggle.com/smid80/weatherww2/data?select=Summary+of+Weather.csv</a>), we can observe in this link that the parameters available in the dataset are:</p><ol><li>STA: Weather Station</li><li>Date: Date of observation</li><li>Precip: Precipitation in mm</li><li>WindGustSpd: Peak wind gust speed in km/h</li><li>MaxTemp: Maximum temperature in degree celsisus</li><li>MinTemp: Minimum temperature in degree celsisus</li><li>MeanTemp: Mean temperature in degree celsisus</li><li>Snowfall: Snowfall and ice pellets in mm</li><li>PoorWeather: A repeat of the TSHDSBRSGF column</li><li>YR: Year of Observation</li><li>MO: Month of observation</li><li>DA: Day of observation</li><li>PRCP: Precipitation in inches and hundreths</li><li>DR: Peak wind gust direction in tens of degrees</li><li>SPD: Peak wind gust speed in knots</li><li>MAX: Maximum temperature in degrees farenheit</li><li>MIN: Minimum temperature in degrees farenheit</li><li>MEA: Mean temperature in degrees farenheit</li><li>SNF: Snowfall in inches and tenths</li><li>SND: Snow depth (includes ice pellets) recorded at 1200 GMT except 0000 GMT in Far East Asian Area in inches and tenths</li><li>FT: Frozen ground top ( depths in inches )</li><li>FB: Frozen Ground Base (depth in inches)</li><li>FTI: Frozen Ground Thickness (thickness in inches)</li><li>ITH: Ice Thickness on Water (inches and tenths)</li><li>PGT: Peak wind gust time (hours and tenths)</li><li>TSHDSBRSGF: Day with: Thunder; Sleet; Hail; Dust or Sand; Smoke or Haze; Blowing Snow; Rain; Snow; Glaze; Fog; 0 = No, 1 = Yes</li><li>SD3: Snow depth at 0030 GMT includes ice pellets in inches and tenths</li><li>RHX: 24-hour maximum relative humidity, as a whole percent</li><li>RHN: 24-hour minimum relative humidity, as a whole percent</li><li>RVG: River guage in feet and tenths</li><li>WTE: Water equivalent of snow and ice on ground in inches and hundredths</li></ol><p>Now, we have a general idea of what the parameters are. We can now decide which ones are relevant. We also need to determine the output parameter.</p><p>As its noted in the problem statement that we need to determine the max temperature or a particular day and I assumed that the result has been expected in degree celsius, hence I have taken <em>MaxTemp </em>as the output parameter.</p><p>Now, in the detail tab of the Summary of Weather.csv in the link, we can understand the kind of data, the number of data, the variatons etc in each of the parameters.</p><p>Now, let us discuss parameter wise, which ones are needed and which ones aren’t.</p><ol><li>STA : As the station number is in no way affecting the max temperature in a particular day, hence this column can be dropped.</li><li>Date: Date is also not a factor contributing to the temperature as far as my understanding goes, hence I have ignored this column.</li><li>Precip: Precipitation in mm is definitely one of the contributors of the temperature of a day as rainfall is an important factor whether the temperature will be high or low on any given day.</li><li>WindGustSpd: The wind speed is also one of the determining factors.</li><li>MinTemp: This shall be used as we have to determine the relation between the min and max temperatures.</li><li>MaxTemp: This is the output parameter</li><li>MeanTemp: This shall be used to determine the relation between the min and max temperatures.</li><li>Snowfall: Obviously this is one of the determining factors of temperature.</li><li>PoorWeather: If the weather conditions have been quantified and a boolean value is provided, it might be useful in determining the temperature in a day.</li><li>YR: The year of observation is not a determining factor of temperature.</li><li>MO: The month of observation is not a determining factor of temperature.</li><li>DA: The day of observation is not a determining factor of temperature.</li><li>PRCP: We already have a column that notes down the temperature in mm, hence we need not have another parameter for the precipitation. Thus, we can ignore this.</li><li>SPD: We already have a column that notes down the wind speed in km/h, hence we need not have another parameter for the wind speed. Thus, we can ignore this. Also, this column does not have any data as 100% of the data is null as written in the description at the the time of writing this post.</li><li>DR: The speed direction is probably an important factor but if we observe carefully, then we can observe that 100% of the values provided are null, hence this column is of no use to us as this does not have any data.</li><li>MAX, MIN, MEA: We are considering the temperatures in degree Celsius and as we already have the corresponding max, min and mean temperatures in degree Celsius we can drop these columns.</li><li>SNF: we already have a snowfall parameter.</li><li>SND: as 95% of the data in this column is null and all the remaining ones are 0, hence I did not think that this column shall be of much use.</li><li>FT, FB, FTI, ITH, PGT, SD3, RHX, RHN, RVG and WTE: All these columns have no data as noted in the description of these columns. Hence, these are of no use.</li><li>TSHDSBRSGF: repetitive column, hence needs to be dropped.</li></ol><p>Thus, after a basic understanding of the data, we can finally decide the columns that we shall be using and these are: Precip, MinTemp, MeanTemp, PoorWeather and Snowfall and the output parameter being MaxTemp.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fww2-weather-linear%2Fv%2F2%26cellId%3D6&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fww2-weather-linear%2Fv%2F2%26cellId%3D6&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/313850aeebc866ed7a080445ee92a029/href">https://medium.com/media/313850aeebc866ed7a080445ee92a029/href</a></iframe><p>Although, we could have seen the data ranges and everything in the link from where we got the data, but it is a good practice to properly represent the data, this further provides us the intuition behind the data.</p><p><strong>Step 4: Visualizing the dataset</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fww2-weather-linear%2Fv%2F2%26cellId%3D7&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fww2-weather-linear%2Fv%2F2%26cellId%3D7&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/43fe130018d13d2db009618fcf3f1289/href">https://medium.com/media/43fe130018d13d2db009618fcf3f1289/href</a></iframe><p>I have used the seaborn library to visualize the dataset. I have used the histogram plot to visualize the data.</p><p><strong>Step 5: Generating the dataset, splitting into training and validation set and creating training and validation data loaders</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fww2-weather-linear%2Fv%2F2%26cellId%3D8&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fww2-weather-linear%2Fv%2F2%26cellId%3D8&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c7161c600c21fb1eb1a8aa2e4dd23a9/href">https://medium.com/media/7c7161c600c21fb1eb1a8aa2e4dd23a9/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fww2-weather-linear%2Fv%2F2%26cellId%3D10&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fww2-weather-linear%2Fv%2F2%26cellId%3D10&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/13316d0d4ff35cfebefb67449c4f65e6/href">https://medium.com/media/13316d0d4ff35cfebefb67449c4f65e6/href</a></iframe><p>Now, let us discuss the code.</p><p>We have first formed the input parameters dataframe and the targets dataframe, as we can see that there are 1,19,040 rows.</p><p>We have then created a TensorDataset <em>dataset</em> , which allows access to rows from <em>inputs</em> and <em>targets</em> as tuples, and provides standard APIs for working with many different types of datasets in PyTorch.</p><p>The TensorDataset returns a tuple (or pair), in which the first element contains the input variables for the selected rows, and the second contains the targets.</p><p>We’ll also create two DataLoaders <em>train_loader</em> and <em>val_loader</em> in which we split the data into batches of a predefined size while training and also for validation. It also provides other utilities like shuffling and random sampling of the data.</p><p>We have split the data using <em>random_split()</em> provided by pytorch which randomly split a dataset into non-overlapping new datasets of given lengths. We have done this splitting by taking 10% of the data as validation set and the remaining 90% for training.</p><p><strong>Step 6: Creating the Linear Regression model</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fww2-weather-linear%2Fv%2F2%26cellId%3D13&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fww2-weather-linear%2Fv%2F2%26cellId%3D13&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/fec25a33101f8d53b82b71c8c2db6d45/href">https://medium.com/media/fec25a33101f8d53b82b71c8c2db6d45/href</a></iframe><p><strong>nn.Linear()</strong></p><p>We have defined a linear model using <em>nn.Linear() </em>which takes 5 inputs and produces one output. The weights of each of the parameters are randomly initialized by pytorch when we define the linear model.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fww2-weather-linear%2Fv%2F2%26cellId%3D11&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fww2-weather-linear%2Fv%2F2%26cellId%3D11&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d336cd9e770fc57858cf05c5c79e6b9/href">https://medium.com/media/9d336cd9e770fc57858cf05c5c79e6b9/href</a></iframe><p><strong>Loss function</strong></p><p>Before we move onto the training and validation steps defined in the model, I would want to discuss about the loss function that has been used in this model, L1 Loss.</p><p>A loss function is a measure of how good a prediction model does in terms of being able to predict the expected outcome. A most commonly used method of finding the minimum point of function is “gradient descent”.</p><p><a href="https://medium.com/@ewuramaminka/mean-absolute-error-mae-sample-calculation-6eed6743838a">Mean Absolute Error</a> (MAE) is another loss function used for regression models. MAE is the sum of absolute differences between our target and predicted variables. So it measures the average magnitude of errors in a set of predictions, without considering their directions. (If we consider directions also, that would be called Mean Bias Error (MBE), which is a sum of residuals/errors). The range is also 0 to ∞.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/0*lOjrx-Fu4a7himVo.png" /></figure><p>There’s an excellent article on loss functions by <a href="https://medium.com/u/2f052b054cee">Prince Grover</a> titled “5 Regression Loss Functions All Machine Learners Should Know” where you can learn more about the various loss functions.</p><p>So, both in the training and validation steps, L1 loss has been used.</p><p><strong>Step 7: Training the model</strong></p><p>I will now talk about the entire training process.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fww2-weather-linear%2Fv%2F2%26cellId%3D15&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fww2-weather-linear%2Fv%2F2%26cellId%3D15&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8497dbe245920e0ccac8ca2bf8105df/href">https://medium.com/media/f8497dbe245920e0ccac8ca2bf8105df/href</a></iframe><p><strong>Optimizer</strong></p><p>Let me start by talking about the optimizer. Instead of manually manipulating the model’s weights &amp; biases using gradients, we can use the optimizer <em>optim.SGD</em> . SGD stands for <em>Stochastic Gradient Descent</em>. It is called stochastic because samples are selected in batches (often with random shuffling) instead of as a single group.</p><p>Note that model.parameters() is passed as an argument to optim.SGD, so that the optimizer knows which matrices should be modified during the update step. Also, we can specify a learning rate which controls the amount by which the parameters are modified.</p><p>The learning rate is also passed to the optimizer as a parameter. This determines how fast the learning process is undertaken or the rate at which the gradient descent proceeds to reach the minimum.</p><p><strong>Training</strong></p><p>We are now ready to train the model. Generally, if we want to define the set of steps to perform training a basic set of steps would look something like:</p><ol><li>Generate predictions</li><li>Calculate the loss</li><li>Compute gradients w.r.t the weights and biases</li><li>Adjust the weights by subtracting a small quantity proportional to the gradient</li><li>Reset the gradients to zero</li></ol><p>We then start the training process for a 100 epochs at a learning rate of 1e-10.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fww2-weather-linear%2Fv%2F2%26cellId%3D17&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fww2-weather-linear%2Fv%2F2%26cellId%3D17&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/45f24ff07aeecafe538f4606450fcc4c/href">https://medium.com/media/45f24ff07aeecafe538f4606450fcc4c/href</a></iframe><p>To understand how the loss function behaves, it is necessary for us to plot the losses.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fww2-weather-linear%2Fv%2F2%26cellId%3D18&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fww2-weather-linear%2Fv%2F2%26cellId%3D18&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/5003bf21fb17364d0f74b26bfc5b5c8f/href">https://medium.com/media/5003bf21fb17364d0f74b26bfc5b5c8f/href</a></iframe><p>We can then save the model as:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2Fww2-weather-linear%2Fv%2F2%26cellId%3D24&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2Fww2-weather-linear%2Fv%2F2%26cellId%3D24&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad1889b987b46a0b621948348414b604/href">https://medium.com/media/ad1889b987b46a0b621948348414b604/href</a></iframe><h3>Conclusion</h3><p>So, I have discussed my thought process while creating a linear regression model and using it to perform a prediction. This is my first attempt both to writing a blog as well as Machine Learning and I hope to share my learning journey with all of you. I am pretty sure, this model can be made better by adding normalization, trying out different learning rates, maybe training for a longer duration but I thought, this clean neat set of steps might help a beginner to create and understand their first model thoroughly as it had helped me. Please share your feedback in comments. Thanks for reading!</p><h3><strong>Further reading</strong></h3><ol><li>Link to my code: <a href="https://jovian.ml/attyuttam/ww2-weather-linear">https://jovian.ml/attyuttam/ww2-weather-linear</a></li><li>More about loss functions: <a href="https://heartbeat.fritz.ai/5-regression-loss-functions-all-machine-learners-should-know-4fb140e9d4b0">https://heartbeat.fritz.ai/5-regression-loss-functions-all-machine-learners-should-know-4fb140e9d4b0</a></li><li>Pytorch learning series: <a href="https://www.youtube.com/watch?v=vo_fUOk-IKk&amp;t=58s">https://www.youtube.com/watch?v=vo_fUOk-IKk&amp;t=58s</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d776947cc2d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/using-linear-regression-to-predict-max-temperature-based-on-weather-conditions-2d776947cc2d">Using Linear Regression to Predict Max Temperature Based on Weather Conditions</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 gradient/derivative related PyTorch functions]]></title>
            <link>https://attyuttam.medium.com/5-gradient-derivative-related-pytorch-functions-8fd0e02f13c6?source=rss-3c7286668559------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fd0e02f13c6</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[jovian-ml]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Attyuttam Saha]]></dc:creator>
            <pubDate>Tue, 16 Jun 2020 05:20:40 GMT</pubDate>
            <atom:updated>2020-06-16T05:21:41.516Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will be talking about the 5 PyTorch functions that I have studied through. Examples will be provided along with scenarios when the functions might break. This article is a great head start to explore PyTorch and the various plethora of functionalities it provides.</p><p>The 5 functions that I will be discussion are:</p><ol><li>detach()</li><li>no_grad()</li><li>clone()</li><li>backward()</li><li>register_hook()</li></ol><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F01-tensor-operations%2Fv%2F3%26cellId%3D1&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F01-tensor-operations%2Fv%2F3%26cellId%3D1&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/383cc93b9806c46fc30b4f2969ba91a7/href">https://medium.com/media/383cc93b9806c46fc30b4f2969ba91a7/href</a></iframe><h3>1. tensor.detach()</h3><p>tensor.detach() creates a tensor that shares storage with tensor that does not require grad. You should use detach() when attempting to remove a tensor from a computation graph. In order to enable automatic differentiation, PyTorch keeps track of all operations involving tensors for which the gradient may need to be computed (i.e., require_grad is True). The operations are recorded as a directed graph. The detach() method constructs a new view on a tensor which is declared not to need gradients, i.e., it is to be excluded from further tracking of operations, and therefore the sub-graph involving this view is not recorded.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F01-tensor-operations%2Fv%2F3%26cellId%3D3&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F01-tensor-operations%2Fv%2F3%26cellId%3D3&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4e499dff4fa30be418c117cf5d3cab8/href">https://medium.com/media/f4e499dff4fa30be418c117cf5d3cab8/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F01-tensor-operations%2Fv%2F3%26cellId%3D4&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F01-tensor-operations%2Fv%2F3%26cellId%3D4&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/cffdf207fb5290e2306bc4dd879058b5/href">https://medium.com/media/cffdf207fb5290e2306bc4dd879058b5/href</a></iframe><p>In the above example we can see that upon using detach(), the value of the gradient of the variable changes. This can be explained as follows: Initially a vector x is defined of size 10 and each element is 1.</p><ol><li>Case 1 — no detach() is used:</li></ol><p>as y is x² and z is x³. Hence r is x²+x³. Thus the derivative of r is 2x+3x². Hence gradient of x is 2.1+3.1² = 5 Thus, x.grad produces a vector of 10 elements each having the value of 5</p><ol><li>Case 2 — detach() is used:</li></ol><p>as y is x² and z is x³. Hence r is x²+x³. Thus the derivative of r is 2x+3x². But as z is calculated by detaching x (x.detach()), hence z is not included when calculating the gradient of x. Hence gradient of x is 2.1 = 2 Thus, x.grad produces a vector of 10 elements each having the value of 2.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F01-tensor-operations%2Fv%2F3%26cellId%3D6&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F01-tensor-operations%2Fv%2F3%26cellId%3D6&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e9dc408db2a4a88e35a8b485494c5d2/href">https://medium.com/media/2e9dc408db2a4a88e35a8b485494c5d2/href</a></iframe><p>In the above scenario, it causes an error, because it detects that a has changed inplace and this will trip gradient calculation. If you comment the c.zero_() or use .clone().detach(), you see that a.grad is 2*a just as it should be.</p><p>It is because .detach() doesnt implicitly create a copy of the tensor, so when the tensor is modified later, it’s updating the tensor on the upstream side of .detach() too. By cloning first, this issue doesnt arise, and all is ok.</p><p>detach doesn’t create copies and should only prevent the gradients to be computed but shares the data.</p><p>Thus, we should use detach() when we don’t want to include a tensor in the resulting computational graph.</p><h3>2. torch.no_grad()</h3><p>Context-manager that disabled gradient calculation.</p><p>Disabling gradient calculation is useful for inference, when you are sure that you will not call Tensor.backward(). It will reduce memory consumption for computations that would otherwise have requires_grad=True.</p><p>In this mode, the result of every computation will have requires_grad=False, even when the inputs have requires_grad=True.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F01-tensor-operations%2Fv%2F3%26cellId%3D10&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F01-tensor-operations%2Fv%2F3%26cellId%3D10&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0a4e3ca48a80180148b548cfa5aceb6/href">https://medium.com/media/e0a4e3ca48a80180148b548cfa5aceb6/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F01-tensor-operations%2Fv%2F3%26cellId%3D11&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F01-tensor-operations%2Fv%2F3%26cellId%3D11&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/c977c39b3630729e5d9687850bebf00a/href">https://medium.com/media/c977c39b3630729e5d9687850bebf00a/href</a></iframe><p>In the above example, “with torch.no_grad():” will make all the operations in the block have no gradients. Hence, we cannot use backward() on the computed variable.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F01-tensor-operations%2Fv%2F3%26cellId%3D13&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F01-tensor-operations%2Fv%2F3%26cellId%3D13&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ca6492e3fc0fd8de1fb3c949b448771/href">https://medium.com/media/0ca6492e3fc0fd8de1fb3c949b448771/href</a></iframe><p>The above example breaks because we are trying to use backward() on r. Using no_grad() ensures that the operations being performed does not have gradients. That is why, r.requires_grad produces False as the output. Hence, this does not have a graident associated with it, when we use r.backward(), the code breaks.</p><h3>3.tensor.clone(<em>memory_format=torch.preserve_format </em>) → Tensor</h3><p>tensor.clone()creates a copy of tensor that imitates the original tensor’s requires_grad field. We should use clone as a way to copy the tensor while still keeping the copy as a part of the computation graph it came from. Gradients propagating to the cloned tensor will propagate to the original tensor.</p><p>tensor.clone() maintains the connection with the computation graph. That means, if you use the new cloned tensor, and derive the loss from the new one, the gradients of that loss can be computed all the way back even beyond the point where the new tensor was created.</p><p>If you want to copy a tensor and detach from the computation graph you should be using</p><p>tensor.clone().detach()</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F01-tensor-operations%2Fv%2F3%26cellId%3D16&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F01-tensor-operations%2Fv%2F3%26cellId%3D16&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b07f3c8b7ccc2aec2a37a337df01b42/href">https://medium.com/media/2b07f3c8b7ccc2aec2a37a337df01b42/href</a></iframe><p>In the above example, we can observe that x_clone is created by performing x.clone(). Thus, a copy of x is set to x_clone. It should be noted that although the variables y and z are obtained using x_clone, when r.backward() is done, the gradients are propagated to the original tensor.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F01-tensor-operations%2Fv%2F3%26cellId%3D18&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F01-tensor-operations%2Fv%2F3%26cellId%3D18&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/c651ab53ea79f2f1f117da1b071a8be2/href">https://medium.com/media/c651ab53ea79f2f1f117da1b071a8be2/href</a></iframe><p>We can observe that we get no value when we try to obtain the gradient of x_clone. This is because x-clone is computed by the clone operation in x, so it is not a leaf variable that it will does not have its grad. But the backpropagation will propagate it to x, so x will get the grad.</p><p>Thus, whenever we want to make a copy of a tensor and ensure that any operations done with the cloned tensor ensures that the gradients are propagated to the original tensor, we must use clone().</p><h3>4. tensor.backward(gradient=None, retain_graph=None, create_graph=False)</h3><p>Computes the gradient of current tensor w.r.t. graph leaves.</p><p>The graph is differentiated using the chain rule. If the tensor is non-scalar (i.e. its data has more than one element) and requires gradient, the function additionally requires specifying gradient. It should be a tensor of matching type and location, that contains the gradient of the differentiated function w.r.t. self.</p><p>This function accumulates gradients in the leaves — you might need to zero them before calling it.</p><p>Parameters gradient (Tensor or None) — Gradient w.r.t. the tensor. If it is a tensor, it will be automatically converted to a Tensor that does not require grad unless create_graph is True. None values can be specified for scalar Tensors or ones that don’t require grad. If a None value would be acceptable then this argument is optional.</p><p>retain_graph (bool, optional) — If False, the graph used to compute the grads will be freed. Note that in nearly all cases setting this option to True is not needed and often can be worked around in a much more efficient way. Defaults to the value of create_graph.</p><p>create_graph (bool, optional) — If True, graph of the derivative will be constructed, allowing to compute higher order derivative products. Defaults to False.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F01-tensor-operations%2Fv%2F3%26cellId%3D22&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F01-tensor-operations%2Fv%2F3%26cellId%3D22&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/9dc994a5e80fdba97c341ed1b606db7b/href">https://medium.com/media/9dc994a5e80fdba97c341ed1b606db7b/href</a></iframe><p>We can observe that upon calling backward() on r, the gradients of the leaf node x is calculated.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F01-tensor-operations%2Fv%2F3%26cellId%3D24&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F01-tensor-operations%2Fv%2F3%26cellId%3D24&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1f1344ed8237f871e37ae08b720a122/href">https://medium.com/media/c1f1344ed8237f871e37ae08b720a122/href</a></iframe><p>We can observe that as the leaf node variable i.e, x does not have requires_grad set to True, hence the backward() function throws an error. Thus, to use backward fuction on a variable, we need to ensure that the leaf nodes that are involved must have requires_grad set to True.</p><p>By default, pytorch expects backward() to be called for the last output of the network — the loss function. The loss function always outputs a scalar and therefore, the gradients of the scalar loss w.r.t all other variables/parameters is well defined (using the chain rule)</p><h3>5. tensor.register_hook(hook)</h3><p>Registers a backward hook.</p><p>The hook will be called every time a gradient with respect to the Tensor is computed. The hook should have the following signature:</p><p>hook(grad) -&gt; Tensor or None</p><p>The hook should not modify its argument, but it can optionally return a new gradient which will be used in place of grad.</p><p>This function returns a handle with a method handle.remove() that removes the hook from the module. Use torch.Tensor.register_hook() directly on a specific input or output to get the required gradients.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F01-tensor-operations%2Fv%2F3%26cellId%3D28&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F01-tensor-operations%2Fv%2F3%26cellId%3D28&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc10d4f5a9d9110eb5ffcfe44a6e5a54/href">https://medium.com/media/fc10d4f5a9d9110eb5ffcfe44a6e5a54/href</a></iframe><p>In the above example, we have registered a lambda function which returns the square of a number which is passed to it. This lambda function is registered as a hook to the tensor variable v. Thus, v is essentially equal to x² where ‘x’ is the variable set to the tensor. Thus, when we do a v.backward, we calculate the gradient of the leaf variable and v is the leaf variable here (because we have defined it, its not a result of computation). Thus, gradient of v is 2x which results to <a href="https://jovian.ml/attyuttam/01-tensor-operations">2, 4, 6</a> as you can see above.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjovian.ml%2Fembed%3Furl%3Dhttps%3A%2F%2Fjovian.ml%2Fattyuttam%2F01-tensor-operations%2Fv%2F3%26cellId%3D30&amp;dntp=1&amp;display_name=Jovian&amp;url=https%3A%2F%2Fjovian.ml%2Fattyuttam%2F01-tensor-operations%2Fv%2F3%26cellId%3D30&amp;image=https%3A%2F%2Fstorage.googleapis.com%2Fjvn%2Fassets%2Fattyuttam%2Fprofile_images%2Ff4c8aa43538c46919ec7f15f4008d6c1%2Fmedium.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=jovian" width="800" height="200" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd67fdddd41312908b3dc4e3cdf4010a/href">https://medium.com/media/fd67fdddd41312908b3dc4e3cdf4010a/href</a></iframe><p>In the above example we get a pretty verbose error “cannot register a hook on a tensor that doesn’t require gradient “. This means that we wont be able to register a hook on a tensor in which the requres_grad parameter is not set to True.</p><p>You could pass a function as the hook to register_hook, which will be called every time the gradient is calculated. This might be useful for debugging purposes, e.g. just printing the gradient or its statistics, or you could of course manipulate the gradient in a custom way, e.g. normalizing it somehow etc.</p><h3>Conclusion</h3><p>In this notebook, I have try to cover five functions that are related to playing with gradients. Using these functions, we can effectively calculate gradients of the leaf nodes and use them at various aspects of development using pytorch.</p><p>Well this is the first story I have ever written. Hope it is of some use to you. Please do throw a clap if you have enjoyed it !</p><h3>Reference Links</h3><p>Provide links to your references and other interesting articles about tensors</p><ul><li>Official documentation for torch.Tensor: <a href="https://jovian.ml/outlink?url=https%3A%2F%2Fpytorch.org%2Fdocs%2Fstable%2Ftensors.html">https://pytorch.org/docs/stable/tensors.html</a></li><li>Pytorch discussion forum: <a href="https://jovian.ml/outlink?url=https%3A%2F%2Fdiscuss.pytorch.org%2F">https://discuss.pytorch.org/</a></li><li><a href="https://jovian.ml/outlink?url=http%3A%2F%2Fwww.bnikolic.co.uk%2Fblog%2Fpytorch-detach.html">http://www.bnikolic.co.uk/blog/pytorch-detach.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fd0e02f13c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>