<?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 Gaurav Rajpal on Medium]]></title>
        <description><![CDATA[Stories by Gaurav Rajpal on Medium]]></description>
        <link>https://medium.com/@gauravrajpal1994?source=rss-a26b76928645------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*x0k_cKJc5YJNSzeP.jpg</url>
            <title>Stories by Gaurav Rajpal on Medium</title>
            <link>https://medium.com/@gauravrajpal1994?source=rss-a26b76928645------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 18:21:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gauravrajpal1994/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[Basics MySQL knowledge required for Data Science.]]></title>
            <link>https://medium.com/analytics-vidhya/basics-mysql-knowledge-required-for-data-science-98530539076a?source=rss-a26b76928645------2</link>
            <guid isPermaLink="false">https://medium.com/p/98530539076a</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[mysql]]></category>
            <dc:creator><![CDATA[Gaurav Rajpal]]></dc:creator>
            <pubDate>Mon, 01 Feb 2021 12:18:29 GMT</pubDate>
            <atom:updated>2021-02-01T15:54:23.499Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*i9MiVHSVX_alw3hUMYo47Q.png" /><figcaption>Source: Internet</figcaption></figure><p>In this blog we will be discuss about the fundamental course of SQL which is useful for all professional be it data analyst, business analyst, data scientist to extract, manipulate or draw insights from data stored in SQL databases. We will be looking at MySQL database starting from introduction, installation and practical sessions.</p><h4>INTRODUCTION :</h4><blockquote>1. Why do we need databases ?</blockquote><p>The rapid explosion of data creates a necessity to have a place to store and retrieve data efficiently. We are actually leaving in age of the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*O8IdAMlorKDH-mYgBTaqYQ.png" /><figcaption>Various sources of data | Source: Analytics Vidhya</figcaption></figure><p>We require the databases mainly for 4 operation i.e. <em>Store, Update, Delete and Search. </em>We really need fast search and as we will see later in the blog which is one of the main reason in using specialization databases.</p><p>As a data scientist perspective we need data to know how to retrieve this data, manipulate it and save the processed data.</p><blockquote>2. What is a database ?</blockquote><p><em>It is an organized collection of data, generally stored and accessed electronically from a computer system.</em></p><blockquote>3. What are the good properties of a database ?</blockquote><p>Eg. Food Recipe Blog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nr7X7u8Dxm42C1RM-Ib72Q.png" /><figcaption>Properties of database | Source: Analytics Vidhya</figcaption></figure><blockquote>4. What are different types of databases ?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*csG0W7SbsOVQNaMBbec12Q.png" /><figcaption>Different types of databases | Source: Analytics Vidhya</figcaption></figure><blockquote>5. How data is stored in database ?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*CO93tk097Kx99uIEWyFsGw.png" /><figcaption>Data Storage | Source: Analytics Vidhya</figcaption></figure><p>As we see in No-SQL type of databases which is schema less and everything is stored as JSON objects we can see we have key-value type of notification. We can nest things at many levels which is not possible in relational databases and hence No-SQL way of defining tables is much more simple and flexible and is much more popular recently.</p><blockquote>6. Which are the list of companies using MySQL ?</blockquote><p><strong><em>80 % of the companies in worldwide uses MySQL</em></strong><em>. </em>Below is the list of companies using MySQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*8mrBK8TDp-WXtekQAXss_g.png" /><figcaption>Companies list using MySQL | Source: Analytics Vidhya</figcaption></figure><h4>INSTALLATION MySQL / MariaDB</h4><p>In this part we will learn how to install MySQL. Please refer the following link for installation of MySQL / MariaDB (MariaDB is fork version of MySQL acquired by Oracle).</p><p>We will be installing MySQL 5.7 for this blog (Windows)</p><p>Installation Links:</p><p><a href="https://dev.mysql.com/downloads/windows/installer/5.7.html">MySQL :: Download MySQL Installer</a></p><h4>GETTING STARTED</h4><p>In this part we will learn we will learn what are types of queries and get started with writing most of the used queries like SELECT &amp; INSERT. We will also look at the data types of MySQL.</p><blockquote>1. What is SQL ?</blockquote><p>SQL stands for ‘<em>Structured Query Language</em>’ . It is a language to communicate with databases. It is standard which means that, it does not depends on any hardware. We can create, maintain and retrieve the information related to database and its data using this language.</p><blockquote>2. History of SQL ?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*WD-KHk-TefHiPjJffBQN9A.png" /><figcaption>History of SQL | Source: Analytics Vidhya.</figcaption></figure><blockquote>3. What are the types of command in SQL ?</blockquote><p>We have following types of SQL statements:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*OKSRNQteWUYfMEXyQaZa8w.png" /></figure><ul><li>DDL (Data Definition Language)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*rviYBL6tBNUiDvsckWLQrA.png" /></figure><ul><li>DML (Data Manipulation Language)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*hlz3fcn9VCntbgOfg71vMg.png" /></figure><ul><li>DCL (Data Control Language)</li></ul><blockquote>4. Exploring Databases.</blockquote><p>In this part we will see how we can create a database and connect to that database and use it for our business purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JInaknWZf7AkqntPSSp9dw.png" /><figcaption>Execution steps for creating database | Source: Analytics Vidhya</figcaption></figure><p>Before creating tables and exploring more let us look at the data types of the MySQL. Ref link is given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LiMZ-cNvbUNKbbyuobk3iw.png" /><figcaption>Data Types in MySQL | Source: Analytics Vidhya</figcaption></figure><p><a href="https://dev.mysql.com/doc/refman/8.0/en/data-types.html">MySQL :: MySQL 8.4 Reference Manual :: 13 Data Types</a></p><blockquote>5. Creating Tables.</blockquote><p>Here we will see how we can create the structure of the table in MySQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*3JHYpNpbVYzOwnfn3ahtbA.png" /><figcaption>Creation of Tables in MySQL | Source: Analytics Vidhya</figcaption></figure><blockquote>6. Inserting Records in Tables.</blockquote><p>Here we will see how we can insert the records in our newly created table User Details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*weBfVZ_ob_bAOpDedOKIZA.png" /><figcaption>Inserting records in tables | Source: Analytics Vidhya.</figcaption></figure><blockquote>7. NULL &amp; NOT NULL.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mBejpc7j2N68KFQyVlEECg.png" /><figcaption>Difference between Null &amp; Not Null | Source: Analytics Vidhya</figcaption></figure><h4>MODIFYING DATABASE STRUCTURE</h4><p>In this part we will see how we can use DELETE and UPDATE command. Also we will see how we can view the structure of the table using DESCRIBE and lastly we will use ALTER command to alter the structure of the table.</p><blockquote>1.UPDATE Command.</blockquote><p><em>UPDATE </em>command is used to update the data in the tables in a database.</p><p><strong>Note:</strong></p><ul><li>Updates can happen only one column at a time.</li><li>Using where clause in an update helps us to update the rows which we are interested in.</li><li>If where clause is not mentioned it will set all rows of <strong><em>column name</em></strong> mentioned to <strong><em>new value.</em></strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tpz9-kRWX9AumMPRgN8EvA.png" /><figcaption>Demonstration of UPDATE command | Source: Analytics Vidhya.</figcaption></figure><blockquote>2.DELETE Command.</blockquote><p><em>DELETE </em>command is use to delete the records from the table.</p><p><strong>Note:</strong></p><ul><li>All the matching rows corresponding to where clause will be deleted from the table.</li><li>If where clause is not used all rows will be deleted.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*aNwj-dOD80czEuGa3ETduw.png" /><figcaption>Demonstration of DELETE command | Source: Analytics Vidhya.</figcaption></figure><blockquote>3. DESCRIBE Command.</blockquote><p><em>DESCRIBE</em> or <em>SHOW CREATE TABLE </em>are basically used to show the structure of the table. The difference between two is that DESCRIBE gives us the structure whereas another one give us the syntax of create table which can used further.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*awiLcYaVoFTAzVsHvmzcdw.png" /><figcaption>Demonstration of DESCRIBE command | Source: Analytics Vidhya</figcaption></figure><blockquote>4. <em>ALTER </em>Command.</blockquote><p>Using <em>ALTER</em> command we can add a column in our table, change it’s name along with change its data type as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*udAomjwxL1dG4m8HcbcT8Q.png" /><figcaption>Demonstration of ALTER command for adding column and changing its name| Source: Analytics Vidhya</figcaption></figure><p>We can also change the datatype of the column using ALTER command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*1zjBCCFjeUHCpvTHUFew-Q.png" /><figcaption>Demonstration of ALTER command for modifying the datatype | Source: Analytics Vidhya.</figcaption></figure><h4>IMPORTING &amp; EXPORTING DATA</h4><p>In this part we will see how we can import and export the data in MySQL which can be in flat files, csv or excel format. We will also see how we can backup the database along with its objects and restore it on another server.</p><blockquote>1. Importing data from CSV to MySQL.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aXqhAMbbR3zf1pK6u2bvoA.png" /><figcaption>Demonstration of loading csv file contents into MySQL tables | Source: Analytics Vidhya</figcaption></figure><blockquote>2. Exporting data from MySQL to CSV.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MfhfyE5q9_IMkmYRScr-_A.png" /><figcaption>Demonstration of exporting data from MySQL into CSV file | Source: Analytics Vidhya</figcaption></figure><blockquote>3. Backing up databases in MySQL.</blockquote><p>In this part we will learn how to backup the databases into SQL file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J_wf-_u9onj1w1AVE3G1cw.png" /><figcaption>Demonstration of backing up database in MySQL | Source: Analytics Vidhya</figcaption></figure><blockquote>4. Restoring database in MySQL.</blockquote><p>Here we will see how we can restore the database which is dropped accidently by the user.</p><p>For restoring the database first we need to create an empty database and then redirect the output SQL file generated in backup phase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*-eQfIL8W7CMkDx7bm0swKQ.png" /><figcaption>Steps for restoring a database in MySQL | Source: Analytics Vidhya</figcaption></figure><h4>DATA ANALYSIS USING MySQL</h4><p>This module plays an important role and we will look at the data analysis part using MySQL. As a data scientist we need to retrieve the insights from the data so this is what this module is all about.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*EqKPuclNQh4DkNEw7DNfBQ.png" /><figcaption>List of modules covered under data analysis module | Source: Analytics Vidhya</figcaption></figure><blockquote>1. Counting Rows &amp; Items.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*w0CEyHrqnk79UeLad3L32A.png" /><figcaption>Demonstration of counting rows and items | Source : Analytics Vidhya</figcaption></figure><blockquote>2. Aggregate Functions (SUM, AVG, STDDEV, MIN, MAX)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CIM-hYi8gva5knXSd6ocJw.png" /><figcaption>Demonstration of aggregate functions | Source: Analytics Vidhya</figcaption></figure><blockquote>3. Slicing required data in MySQL.</blockquote><p>In this part we will see IN, OR, NOT operators. Also we will see AND and BETWEEN operators of where clause.</p><p><strong><em>IN OPERATOR:</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*phbjUQSF4ry62GyaExsgRw.png" /><figcaption>Demonstration of IN Operator in My SQL | Source: Analytics Vidhya</figcaption></figure><p><strong>NOT IN OPERATOR:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*y6FFHCpuI6RxdIFdG95ang.png" /><figcaption>Demonstration of NOT IN Operator in MySQL | Source: Analytics Vidhya</figcaption></figure><p><strong>BETWEEN OPERATOR:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*3eEvpUREIEvv4262Y4mQeg.png" /><figcaption>Demonstration of BETWEEN in MySQL | Source: Analytics Vidhya</figcaption></figure><blockquote>4. Limiting the data in MySQL.</blockquote><p>In this part we will see how we can limit the number of rows to view from our tables.</p><p>We can limit the number of rows using LIMIT keyword.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*55C-BwHsrk-U9k_b6VDQAg.png" /><figcaption>Demonstration of number of rows in MySQL | Source: Analytics Vidhya</figcaption></figure><blockquote>5. Sorting data in MySQL.</blockquote><p><strong>ASCENDING ORDER:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*CfbIaRrFhTJQ9oPC6C4YPA.png" /><figcaption>Demonstration of sorting salary in ASCENDING order and getting 2nd lowest salary | Source: Analytics Vidhya</figcaption></figure><p><strong>DESCENDING ORDER:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*BekfxAGjsqWAooDu14Yo8Q.png" /><figcaption>Demonstration of sorting salary in DESCENDING order and getting 2nd largest salary | Source: Analytics Vidhya</figcaption></figure><blockquote>6. Filtering patterns using LIKE and wildcard in MySQL.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*naoII0fOpZDhOxrK82kE3g.png" /><figcaption>Demonstration of filtering operation in MySQL | Source: Analytics Vidhya</figcaption></figure><blockquote>7. Grouping, Rolling up and Filtering in group in MySQL.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*eg27tbi9u_u1WwiqjA9bFg.png" /><figcaption>Getting count of unique department | Source: Analytics Vidhya</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*otO48Oug0gFT77bZrpRztA.png" /><figcaption>Examples of filtering rolled up data in MySQL | Source: Analytics Vidhya</figcaption></figure><h4><strong>DESCRIPTIVE ANALAYSIS: FIFA 2019</strong></h4><p><a href="https://github.com/grajpal123/Descriptive-Analaysis-using-MySQL-FIFA-2019">grajpal123/Descriptive-Analaysis-using-MySQL-FIFA-2019</a></p><p>The above link consists a project using MySQL queries. We have done descriptive analysis on FIFA 2019 players dataset.</p><h4>WORKING ON JOINS IN MySQL.</h4><p>In real scenario data is not stored in a single table. It is stored in multiple tables. In this module we will see how we can get the data from multiple tables using something known as joins and subqueries.</p><h4>Types of Joins.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*uDz0CMzZ-tkH2_HI85QnuA.png" /><figcaption>Types of Joins in MySQL | Source: Analytics Vidhya</figcaption></figure><blockquote>1.Left Join.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N-bIlsFyX2GTjN56eeHFuw.png" /><figcaption>Description about LEFT JOIN | Source: Analytics Vidhya</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*aUhUJ2-_ZX-l6jDs1NV2QQ.png" /><figcaption>Practical examination LEFT JOIN | Source: Analytics Vidhya</figcaption></figure><blockquote>2. Inner Join.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v3C7erlR0tJ5TVIQPJyGQg.png" /><figcaption>Description about INNER JOIN | Source: Analytics Vidhya</figcaption></figure><blockquote>3. Cross Join / Cartesian Join.</blockquote><p>We must note that this type of join is rarely used in practice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U4iu63WowJHmu971R5MzMg.png" /><figcaption>Description about CROSS JOIN | Source: Analytics Vidhya</figcaption></figure><blockquote>4. Right Join.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*56_DKYbGXSP88GEaDvzplA.png" /><figcaption>Description about RIGHT JOIN | Source: Analytics Vidhya</figcaption></figure><blockquote>5. Self Join.</blockquote><p>Self Join is a scenario where we join a table to itself. It is complex to debug and must be use only when we require pair wise list. Eg. Pairwise players belonging to same club in FIFA_2019 dataset or pairwise distribution of players whose age difference is less than 10.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ABIyXrZ63vRe-B3jPJMdQ.png" /><figcaption>Description about SELF JOIN | Source: Analytics Vidhya</figcaption></figure><h4>INTRODUCTION TO INDEXING</h4><p>Indexing helps us to make query and search fast in the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*vU7J9bQjFd81HbGa66A2tw.png" /><figcaption>Description about INDEX |Source: Analytics Vidhya</figcaption></figure><blockquote>1. How indexing works ?</blockquote><p>Let us consider the example of Library and understand a scenario where indexing will help us for faster search.</p><p>Case 1: If there is a scene that a new book has comes in and along with that there are few other books as well which needs to updated or removed or have become outdated. So if a librarian keep a new book on some random self so to find that book next time it will take a lot of time.</p><p>Case 2: If a smart librarian has sorted all the books based on the subject followed by author in alphabetical order then keeping a new book which belongs to XYZ subject for XYZ author becomes easier for fetching.</p><p>So, considering the case 2 we can say that, indexing on subject followed by author will make our search faster and will also help us for insertion, updating selves followed by removing outdated books without any difficulty.</p><blockquote>2. Relationship.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*pTJfSRBt4WIRJwe7OsJqHw.png" /><figcaption>Types of Relationship | Source: Analytics Vidhya</figcaption></figure><blockquote>3. Table Constraints.</blockquote><p>Table constraints put constraints on the data which is inserted in the table. If we try to insert data violating that constraint MySQL won’t allow us to insert that data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*kyzxHitgD0_soprMuig3og.png" /><figcaption>Description about Table Constraints | Source: Analytics Vidhya</figcaption></figure><h4>MySQL BUILT IN FUNCTIONS.</h4><p>In this section we will discuss about some of the built in functions used in MySQL which can help us in reporting.</p><blockquote>1.String Function: CONCAT</blockquote><p>This function is used to concatenate strings from the data. For eg. if we need to concatenate first and last name of the person from the data. We use the <strong><em>concat</em></strong> keyword in MySQL to achieve this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*r-lz_utW7RIoKbuAnIZ51A.png" /><figcaption>Example of CONCAT operation | Source: Analytics Vidhya</figcaption></figure><blockquote>2. String Function: CASE</blockquote><p>This function is use to convert strings into lowercase or uppercase. We use <strong><em>ucase</em></strong> <strong><em>(UPPER)</em></strong> or <strong><em>lcase (LOWER) </em></strong>keyword in MySQL to achieve this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*c4O0VB99XUi6e2L2Lfi8mg.png" /><figcaption>Example of CASE operation | Source: Analytics Vidhya</figcaption></figure><blockquote>3. String Function: Trimming Strings</blockquote><p>This function is use to remove trailing and leading spaces in a string. We use <strong><em>ltrim</em></strong>, <strong><em>rtrim </em></strong>and <strong><em>trim</em></strong> functions of MySQL to achieve this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*GE7c40TO-sJDoWPjUWSzEg.png" /><figcaption>Example of TRIMMING strings | Source: Analytics Vidhya</figcaption></figure><blockquote>4. String Function: Extracting / Slicing Strings</blockquote><p>This is use to extract some part of strings. We use <strong><em>left, right</em></strong> and <strong><em>substring</em></strong> keyword for extracting first, last and some characters of string.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*ZSxWfh8F10LzrNpg5xn0_w.png" /><figcaption>Example of SLICING strings | Source: Analytics Vidhya.</figcaption></figure><blockquote>5. Date-Time Functions: Current Date &amp; Time.</blockquote><p>We use <strong><em>now()</em></strong> function to get the current date along with timestamp. Along with that we can also use <strong><em>curdate()</em></strong>, <strong><em>curtime()</em></strong>, <strong><em>unix_timestamp() </em></strong>and observe the following result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*hQJI9v1P-qSBQVu6SSGNJQ.png" /><figcaption>Example for getting current date and time using MySQL functions | Source: Analytics Vidhya</figcaption></figure><blockquote>6. Date-Time Functions: Extracting Date &amp; Time.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*NqXcM7Lanf_UdYduNRRY4g.png" /><figcaption>Examples for extracting date and time from a particular column in MySQL | Source: Analytics Vidhya</figcaption></figure><blockquote>7. Date-Time Function: Extracting Month / Day / Year</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*5BZR-orcioX_Jif5jakShQ.png" /><figcaption>Example for extracting Month / Day / Year from a particular column in MySQL | Source: Analytics Vidhya</figcaption></figure><blockquote>8. Date-Time Function: Formatting Date-Time</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*kyei3hfHRtDLZURGXds4rw.png" /><figcaption>Example of formatting date column with required date format | Source: Analytics Vidhya</figcaption></figure><blockquote>9. Numeric Functions</blockquote><p>There are various numeric functions which are used in MySQL. We will see following function:</p><ol><li><strong><em>round()</em></strong> function which is used to round the number to nearest integer.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*pGrrpYbv0wtKrSwqanLrmQ.png" /><figcaption>Example of ROUND function in MySQL| Source: Analytics Vidhya</figcaption></figure><p><strong><em>2. floor()</em></strong> function which is use to round down the values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*gBbIV2RN16VawezTZRx-bw.png" /><figcaption>Example of FLOOR function in MySQL | Source: Analytics Vidhya</figcaption></figure><p><strong><em>3.ceil() </em></strong>function which is used to round up the values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*CC-4jBol_pS2ZAuCXCL-xg.png" /><figcaption>Example of CEIL function in MySQL | Source: Analytics Vidhya</figcaption></figure><p><strong><em>4.truncate()</em></strong> function which help us to display number of the decimal points required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*bKgrJnYg8MGHPlr2Ht1z_w.png" /><figcaption>Example of TRUNCATE function in MySQL | Source: Analytics Vidhya</figcaption></figure><p><strong><em>5. abs()</em></strong> functions to remove the negative sign of the numbers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*69sZvxPF1C8wwVitwKLLIg.png" /><figcaption>Example of ABS function in MySQL | Source: Analytics Vidhya</figcaption></figure><h4>MySQL WINDOWS FUNCTIONS</h4><p>MySQL windows functions are used to perform data analysis calculation more easily. We will be using <strong><em>OVER()</em></strong> and <strong><em>PARTITIONED BY</em></strong> quite often if we want to use windows function.</p><p>OVER(): It determines the window (set of rows)</p><p>PARTITIONED BY : It splits the result into partitions where window function is applied.</p><p><a href="https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html">MySQL :: MySQL 8.0 Reference Manual :: 12.20.1 Aggregate Function Descriptions</a></p><p>To demonstrate windows functions we will be creating demo database called <strong>SALES. </strong>Consider the schema of the database / table below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*JEz6kdK35-YheAdTIdEdig.png" /><figcaption>Schema of sales DB | Source: YouTube (SQL Tutorial — Window Functions by Bearded Dev)</figcaption></figure><blockquote>1. To get Total amount / Sales.</blockquote><p>To get the <strong><em>total amount per sales</em></strong> and then populate back to the main table we would have use CTE (Common Table Expression). The query along with the output is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z55CaIGN2-3quw9nrGnnvA.png" /><figcaption>Demonstration of CTE function in MySQL | Source: YouTube (SQL Tutorial — Window Functions by Bearded Dev)</figcaption></figure><p>Now to debug and grasp the above query is little bit difficult. It is also not easiest to read. So, here comes the windows function to rescue us from this problem where we will be using <strong><em>OVER</em></strong> clause which helps us to divide the data in windows and use <strong><em>PARTITION BY</em></strong> clause along with it to further break down the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VHZskvl1g6jbUcXfTBETXQ.png" /><figcaption>Demonstration of Windows Function | Source: YouTube (SQL Tutorial — Window Functions by Bearded Dev)</figcaption></figure><blockquote>2. To get Number of Line Amount / Sales along with Total Sales.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PSm2La13aldbyuDJAEIlLg.png" /><figcaption>Demonstration of Windows Function | Source: YouTube (SQL Tutorial — Window Functions by Bearded Dev)</figcaption></figure><blockquote>3. To get the Daily Sales.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*edXbxZ4WYeR7yb1WiYmjuw.png" /><figcaption>Demonstration of Windows Function | Source: YouTube (SQL Tutorial — Window Functions by Bearded Dev)</figcaption></figure><p>Conclusion</p><p>So, in this blog we learnt basic MySQL knowledge required for any Data Scientist. We started with introduction and understanding the history. We defined what are DDL, DML and DCL commands. We studied about them in details and explored them with examples. We understood how analysis can be carried out by writing SQL queries and did descriptive analysis of FIFA_2019 players project. We also understood what are various types of joins and built in functions. Last but not the least we understood the windows functions which can be helpful in reporting purposes.</p><p>Hope you understood the basic intuition behind this blog.</p><p>Do connect with me on LinkedIn : <a href="https://www.linkedin.com/in/gaurav-rajpal/">https://www.linkedin.com/in/gaurav-rajpal/</a></p><p><strong><em>If you liked it please give 50 applauses.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/0*Q6SMwWM7WTnN7XVE.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98530539076a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/basics-mysql-knowledge-required-for-data-science-98530539076a">Basics MySQL knowledge required for Data Science.</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Comprehensive Guide to Convolution Neural Network]]></title>
            <link>https://medium.com/swlh/a-comprehensive-guide-to-convolution-neural-network-86f931e55679?source=rss-a26b76928645------2</link>
            <guid isPermaLink="false">https://medium.com/p/86f931e55679</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <dc:creator><![CDATA[Gaurav Rajpal]]></dc:creator>
            <pubDate>Fri, 20 Nov 2020 17:55:26 GMT</pubDate>
            <atom:updated>2020-11-23T08:33:08.809Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nohz-_aAh_kFebQuRUwyZA.png" /><figcaption>Source: Internet</figcaption></figure><p>In this blog we will be focusing on what are convolution neural networks and how do they work.</p><p>The Convolution Neural Network or CNN as it is popularly known is the most commonly used deep learning algorithm. Before we get into how CNN works let us first understand the problems faced during traditional MLP and why do we need CNN at first place.</p><p><strong>ISSUES WITH TRADITIONAL MLP &amp; WHY WE NEED CNN ?</strong></p><p>Let us start with simple example,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*WYvKp7MrkV-d6MdMl6x6OA.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>In the example shown above we would find it difficult to explain what exactly the image on our left means but when we look at the image on our right we immediately recognize that it is an image of a dog. Interesting thing is that both of the images are same. The image on the right is 2D image of a dog whereas the image on the left is just 1D image. Not only humans but computers also do find it difficult to recognize an image represented in 1D.</p><p>Let us consider another scenario,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*Y97-lyDnqNrgd9pS6BTbnQ.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>In the above figure, first image is normal image of a dog while second image is manipulated one in which we have swap nose and the eye. Looking at the current form it makes us easy to identify the abnormalities in the images but in case of 1D it is very difficult to figure out these abnormalities. This is first problem with MLP i.e. <strong><em>Losing Spatial Orientation of Image. </em></strong>We must remember that a dog is a dog only when the nose, eyes, ears etc. are relatively present where they should be. Any changes in the relative position does not qualifies that image to be a dog.</p><ul><li>MLP uses 1D representation of an image to identify or classify these images whereas CNN uses 2D representation to identify them. Thus CNN preserves the spatial orientation .</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*6Wu-qwVi6WMBa0G8tsLjhQ.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><ul><li>The other issue with MLP is more on computational side of things.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*hO1vbs-XRbW5LGd64OxFgg.png" /></figure><p>If we consider the adjoining image and create a neural network using 1000 neurons the nos. of parameters which is the weight matrix would be about 10⁶ .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*NgdtOu849JAHgam3k56MUA.png" /></figure><p>If we consider the adjoining image with more nos. of pixels and build a neural network the nos. of parameters in this case would be 600 x 10⁶ (600 million).</p><p>Both the situation will be a nightmare for our computer system.</p><p>Thus the issue which we saw considering the two images of various dimensions and building neural network using single hidden layer is is called as <strong><em>Parameter Exploration in Neural Network.</em></strong></p><p>Dealing with above two problems i.e. <strong><em>Losing Spatial Orientation</em></strong><em> </em>and <strong><em>Parameter Exploration in Neural Network </em></strong>is built in CNN. It preserve the spatial orientation and also reduces the number of trainable parameters in neural network.</p><p><strong>BASIC STRUCTURE OF CNN.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*yK7LgXQJlYpxKbhFHAgH1w.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>In MLP (multilayer perceptron) if we remember hidden layer was responsible for generating features. Now in CNN apart from above 3 layers we also have convolution layer. The convolution layer uses 2D input which helps to solve above issue which we discussed and also it acts like a feature extractor. So, in CNN we have convolution layer and hidden layers acting as feature extractor. These features are been extracted using <strong><em>filters</em></strong> which we will be discussing further.</p><p><strong>ROLE OF FILTERS IN CNN.</strong></p><p>As we saw in the structure of CNN, convolution layers is used to extract the features and for extracting features it uses filters. So, let us discuss about how the features are extracted using filter now.</p><p>Consider below image ,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_He1gKliCusLvvRuWH0IJg.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>In the above image we used various filters like Prewitt or Sobel and obtained the edges. For detail understanding about working on the images and extracting edges you can shoot up at my below blog for theoretical and practical implementation.</p><p><a href="https://medium.com/analytics-vidhya/getting-started-with-image-data-deep-learning-328faad6d929">Getting Started with Image Data — Deep Learning</a></p><p>Let us understand how filter operation basically works using an animated image.</p><blockquote><strong>HOW DOES FILTER OPERATION WORKS ?</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*VFbNHdrVYdE0AIKVCY3blw.gif" /><figcaption>Convolution Operation on 5x5 with 3x3 filter</figcaption></figure><p>Suppose we have matrix of numbers representing an image and we take 3x3 filter and perform element wise multiplication using the filter over the image. The result which is obtained after performing filter operation is stored in new matrix called as <strong><em>Feature Map.</em></strong></p><p>The filter moves over the image in a manner how we write over the paper i.e. left to right. The nos. of pixels that the filter moves in horizontal direction is called as <strong><em>column stride</em></strong>. The nos. of pixels that the filter moves in vertical direction is called as <strong><em>row stride</em></strong>. This operation is known as <strong><em>convolution operation </em></strong>where<strong><em> </em></strong>filter slides through the image performs element wise operation and generates new matrix called as feature map.</p><blockquote><strong>UNDERSTANDING THE DIMENSIONS.</strong></blockquote><p>Now we know how the feature map is calculated let us look at the dimensions of input image, filter and feature map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*1qKU4vLJYJKQtiw8glyObQ.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>In the above figure we have an input image of size (13 x 8) followed by filer of size (3 x 3) and feature map of size (11 x 6 ) obtained by convolution operation.</p><p>Consider below images,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*FoIybKxF75EtWCdXRBMNog.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>When the filter is used over the first patch of an input image it compares the pixel values on the right and the left on the target pixel 34 and stores the resultant value in feature map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*AJ1N6ntMw2r65zhri7hR_A.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>Basically feature map contains values against the pixel highlighted in the green box but pixels on the edges are not taken into account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*1n3QD0yTYnu4rjI8iWArmg.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>If we consider a pixel on an edge i.e. pixel 36 we will notice that there are no pixel surrounding the highlighted pixel and hence it is not contributing in convolution operation and hence size of feature map becomes smaller after every convolution operation.</p><blockquote><strong>PADDING STRATEGIES.</strong></blockquote><p>As we understood in previous section that pixels on the boundary do not contribute in convolution operation so to resolve that issue let us understand padding strategies.</p><p>While building a convolution layer we can set the padding strategies which can be of 2 types.</p><ul><li><strong>SAME</strong> : Feature map and input image are of same size since zeros are added around the edges of the image.</li><li><strong>VALID </strong>:Feature map and input image differ in size since zeros are not added.</li></ul><p>Imagine if we had an image of 1300 x 800 we cannot go and count every single value in output image so you all can refer below formula to calculate height and width of our output i.e. feature map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*JmTDho-N3cLWXlhhMQBk4A.png" /><figcaption>Source: Analytics Vidhya.</figcaption></figure><p>There are few important things we must note here:</p><ul><li>Each convolution layer can have multiple filters.</li><li>Values in the filter are not fixed and are learnt during the training process.</li><li>It is like MLP where we had parameters like weight matrix which was learnt during backpropagation process here in CNN we have filter values which are learnt during backpropagation.</li></ul><p>Using the above formula as discussed let us try to understand the dimensions of the feature map on gray scale images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*FxhZDfssF1A5z87IcfcBbA.png" /><figcaption>Shape with 1 filter and 2D image.</figcaption></figure><p>Now instead of single filter, if we use n filters in this case we will have n feature maps stacked together. Values in the filters can be different and are learnt during backpropagation hence we can also have different feature maps of a single input image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*Ku7tLmWub1q5LmPKCJSphg.png" /><figcaption>Shape with n filters and 2D image.</figcaption></figure><p>Lets us look at the scenario where our input images are having more than one channel i.e. RGB image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aWtbkAdNBcZQ-kjlQ4MRtg.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>Using the above image we cannot use our 2D filter for convolution operation as nos. of channels in the filter should be same as nos. of channels in an input image. Interestingly if we use RGB image along with 2D filter, the deep learning frameworks automatically handles it. We do not have to mention the nos. of channels. Note that the output of the operation will be 2D image.</p><p>Illustration :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*7qYXBohw2EAzIx9w14c92A.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>Now instead of 9 values generating single value in a feature map, we will now have 27 values which will be contributing in generating a single value in feature map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zv31eWU4mgCObjiD5a6GCQ.gif" /><figcaption>Source: Internet</figcaption></figure><p><strong>LOCAL CONNECTIVITY &amp; PARAMETER SHARING IN CNN.</strong></p><p>In local connectivity output pixel values takes input from a (small) local group of pixel values from the complete image. It is same as convolution operation i.e. filter multiplication happening element by element wise. If we compare with MLP (multi layer perceptron) each and every input value use to get multiplied by weight.</p><p>The architecture of CNN (<em>discussed in later section) </em>assures that the learnt filter produces strongest response to spatially local input patterns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zzw9R_qXoke825OYkmtv9Q.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>In parameter sharing all pixels in an input image share same filter matrix. If we compare with MLP each input and hidden layer where assigned different weight so nos. of trainable parameters was dependent on input size but in this case for complete input image irrespective of size of input image we use same filter map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VMaHXc-xWvs2fKMzERITTw.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p><strong>ARCHITECTURE OF CONVOLUTION NEURAL NETWORK.</strong></p><p>Now comes the exciting part of this blog where we will understand the architecture of our convolution neural network in parts.</p><blockquote><strong>CONVOLUTION LAYER <em>:</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_hNo-D6N2jtmCDt12qlndQ.png" /><figcaption>Output of Successive Convolution Layer.</figcaption></figure><p>Consider we have 1000 images of size (200x200x3). Now this input is sent to convolution layer where we have 32 filters each of dimension (3x3x3). Considering column and row stride as1 and padding strategy as valid the shape of the output from convolution layer 1 would be (1000x198x198x32) where 1000 is nos. of images and (198x198x32) represent the dimensions of single input image. After convolution operation we use activation function to introduce non-linearity. It does not change the dimension of the output.</p><p>Now we introduce another convolution layer with 64 filters and size (3x3x32). As we have 32 channels in our input which was the output of convolution layer 1. The output after this operation would be (1000x196x196x64) where (196x196x64) represent the dimension of image in second convolution layer.</p><p>So, this is how we calculate the shape of the output after series of convolution layer.</p><p>But, note that the output of convolution layer is a 3D matrix and is not the final output of the architecture. After convolution layers we add the hidden layer which is also called as fully-connected layer. As we have seen in MLP(multilayer perceptron) it takes inputs of 1D so our 3D output obtained from convolution layer will be converted into 1d and the size of images in FC layer will be (1000, 196x196x64) i.e. 24,58,624. This process is called know as <strong><em>Flattening.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*KMuOjo4DX60PCDnmj3lA_g.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>Considering the above image we see that in FC layer against every 1000 images we have almost 24 lacks features. So if we see the input for FC layer is very huge nos. So, in order to deal with this scenario we use another layer called as <strong><em>Pooling Layer</em></strong>.</p><blockquote><strong>POOLING LAYER :</strong></blockquote><p>Pooling layer are used mainly for dimensionality reduction and since they reduce the dimension they make the computation easier and training much faster. There are two main techniques of pooling i.e. <strong><em>Max Pooling &amp; Average Pooling. </em></strong>Before we get into the details of these techniques let us understand how pooling works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*phlnZg9roAjpR983JhZmrg.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>Let us consider 2D input image of size 4x4 and window size of 2x2 with stride as one. Since window size is 2x2 we select 2x2 patch from input image, perform some mathematical operation and generate the output.</p><p>Let us now understand how do we calculate these values,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*7ZLLprpbQjPFW3R2b97z0Q.gif" /><figcaption>Source: Internet</figcaption></figure><p>The example what we discussed so far was of 2D input. What if we have RGB image. <strong><em>We must remember that pooling reduces the dimensions across the height and width of an image not across the channels.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*1HWGkEn6CMXt71aaxvc2fw.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>There are few more pooling techniques which are also used like <strong><em>GlobalAveragePooling &amp; GlobalMaxPooling </em></strong>where will be be having average or max value from all the channels and it is generally used at the final layer to convert our 3D input into 1D.</p><blockquote><strong>FORWARD PROPAGATION IN CNN.</strong></blockquote><p>In forward propagation, convolution layers extracts features from input image with the help of filters and the output which is obtained is sent to hidden layer where hidden layer uses the weights and bias along with the inputs in order to calculate the output. In the backward propagation process these filter values along with weights and bias values are learnt and constantly updated.</p><p>For now, let us focus on forward propagation and understand it better and in upcoming section we will discuss about forward propagation.</p><p>For simplicity purpose I have consider single convolution layer and single neuron in hidden layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*ZA_n8T2DpJwg8iW8eCadqw.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><blockquote><strong>BACKWARD PROPAGATION IN CNN</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LbtS-o7YuNQMyirRcAimeQ.png" /></figure><p>In backward propagation we compare the output obtained with the predicted output and calculate the error. If the error is large we can say that predictions are large from the actual values. Now this error value depends upon 3 parameters i.e. weights, bias and filter values. During back propagation these values are updated.</p><p><strong>Conclusion</strong></p><p>So, in this blog we learnt about various issues like <strong><em>spatial orientation</em></strong> along with <strong><em>parameter explode. </em></strong>Further we discussed above <strong><em>convolution layer, pooling layer, forward propagation and backward propagation</em></strong>.</p><p>Hope you understood the basic intuition behind all these layers which are used for building CNN and used in Transfer Learning.</p><p>Connect with over LinkedIn.</p><p><a href="https://linkedin.com/in/gaurav-rajpal">Gaurav Rajpal - Data Science Aspirant - AnalytixPRO | LinkedIn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86f931e55679" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/a-comprehensive-guide-to-convolution-neural-network-86f931e55679">A Comprehensive Guide to Convolution Neural Network</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[Simple Loan Prediction Project using Neural Network.]]></title>
            <link>https://medium.com/analytics-vidhya/simple-loan-prediction-project-using-neural-network-bdac5e945fcc?source=rss-a26b76928645------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdac5e945fcc</guid>
            <category><![CDATA[loans]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-neural-network]]></category>
            <dc:creator><![CDATA[Gaurav Rajpal]]></dc:creator>
            <pubDate>Fri, 13 Nov 2020 06:37:30 GMT</pubDate>
            <atom:updated>2020-11-15T16:49:56.624Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*iGTB7xvQa4qVIo4-OvlfYQ.png" /><figcaption>Source: Internet</figcaption></figure><p>In this project we will be solving about loan prediction problem where we have to <strong>predict whether based on customer details loan should be approved or not</strong>. Here is the glance of the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*zTrOAXEMHSDz4cZPWDmkMQ.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>We have various independent variables ranging from <strong><em>Education, Income, Loan Amount, Credit History</em></strong> etc. and one target variable <strong><em>Loan Status</em></strong>. Since we have two values in our target variable ‘Y’ which represent Loan Approved and ’N’ which represents Loan Not Approved.</p><p>Let us dig dive into the problem and approach it step by step.</p><blockquote><strong>STEP 1: DATA PREPROCESSING STEP: </strong>As models are addicted to numbers, some of data preprocessing steps which we will be looking at in this project are as follows.</blockquote><ol><li><em>Filling null values / missing values</em> .</li><li><em>Converting categorical values into number</em>.</li><li><em>Bring all variables to same scale between (0 to 1) which reduces computation time and helps neural network to converge faster</em>.</li></ol><p><strong>MISSING VALUES.</strong></p><ol><li>Categorical Values.</li></ol><pre># Checking Null Values.</pre><pre>data.isnull().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*2bxII5abMWS2bDj4aav2vA.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>We have multiple null values existing in our independent variable columns. We will handle them one by one.</p><pre># Handling Categorical Null Values </pre><pre>-&gt; Gender<br>data[&#39;Gender&#39;].fillna(data[&#39;Gender&#39;].mode()[0],<br>                      inplace = True)</pre><pre>-&gt; Married<br>data[&#39;Married&#39;].fillna(data[&#39;Married&#39;].mode()[0],<br>                       inplace = True)</pre><pre>-&gt; Dependent<br>data[&#39;Dependent&#39;].fillna(data[&#39;Dependent&#39;].mode()[0],<br>                         inplace = True)</pre><pre>-&gt; Education<br>data[&#39;Education&#39;].fillna(data[&#39;Education&#39;].mode()[0],<br>                         inplace = True)</pre><pre>-&gt; Self_Employed<br>data[&#39;Self_Employed&#39;].fillna(data[&#39;Self_Employed&#39;].mode()[0],<br>                             inplace = True)</pre><p>2 . Continuous Values.</p><pre>plt.figure(figsize = (10,4))</pre><pre>sns.boxplot(x = &#39;LoanAmount&#39;,<br>            data = data,<br>            orient = &#39;horizontal&#39;)</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*MyPpCsMjQKWd2R0Xh3g3Gg.png" /></figure><p>As we have many outliers in LoanAmount column, we will impute the missing values with median as median does have any effect on outliers.</p><pre>data[&#39;LoanAmount&#39;].fillna(data[&#39;LoanAmount&#39;].median(),<br>                          inplace = True)</pre><p><strong>HANDLING CATEGORICAL VALUES.</strong></p><pre># Converting the categories into numbers using map function.</pre><pre>data[&#39;Gender&#39;] = data[&#39;Gender&#39;].map({&#39;Male&#39;: 0, &#39;Female&#39;: 1})</pre><pre>data[&#39;Married&#39;] = data[&#39;Married&#39;].map({&#39;No&#39;: 0, &#39;Yes&#39;: 1})</pre><pre>data[&#39;Dependents&#39;] = data[&#39;Dependents&#39;].map({&#39;0&#39;: 0, &#39;1&#39;: 1, &#39;2&#39;: 2, &#39;3+&#39;: 3})</pre><pre>data[&#39;Education&#39;] = data[&#39;Education&#39;].map({&#39;Graduate&#39;: 1, &#39;Not Graduate&#39;: 0})</pre><pre>data[&#39;Self_Employed&#39;] = data[&#39;Self_Employed&#39;].map({&#39;No&#39;: 0, &#39;Yes&#39;: 1})</pre><pre>data[&#39;Property_Area&#39;] = data[&#39;Property_Area&#39;].map({&#39;Rural&#39;: 0, &#39;Semiurban&#39;: 1, &#39;Urban&#39;: 2})</pre><pre>data[&#39;Loan_Status&#39;] = data[&#39;Loan_Status&#39;].map({&#39;N&#39;: 0, &#39;Y&#39;: 1})</pre><p><strong>SCALING THE VALUES - MIN MAX SCALER.</strong></p><p>We will be using min-max scaler which scales down the value of all columns between 0 to 1. The formula for min-max scaler is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*UyT3wNJvWE4G5AA0UXiJfw.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><pre>for i in data.columns[1:]:<br>    data[i] = (data[i] - data[i].min()) / (data[i].max() - data[i].min())</pre><blockquote><strong>STEP 2: STEPS TO BUILD NEURAL NETWORK. </strong><em>Here we will discuss the steps which are required to build a neural networks.</em></blockquote><ol><li><em>Loading the data</em>.</li><li><em>Creating training and validation data</em>: We will train on train data and validate on validation data.</li><li><em>Defining the architecture of our model</em>: We will define how many input neurons, nos. of neurons in hidden layer and output layer.</li><li><em>Compile the model (loss function / optimizers)</em>: Here we will be defining our cost function which will be used during backward propagation.</li><li><em>Train the model: </em>We will train our model and define nos. of epochs.</li><li><em>Evaluate models performance on training and validation data</em>.</li></ol><p><strong>TRAINING &amp; VALIDATION: </strong>Here, we will be playing with our training data. Out of 100% of training data we will keep 10% for testing data and evaluate the model’s accuracy on it. This test data would be totally unseen by the model. Out of remaining 90% of training data we will use 20% for validating our model and train on 70% of the data.</p><pre># Testing Data - 10%<br>from sklearn.model_selection import train_test_split<br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.1, stratify=data[&#39;Loan_Status&#39;], random_state = 42)</pre><pre># Train &amp; Valid Data - 90%<br>x_train, x_val, y_train, y_val = train_test_split(X_train, y_train, test_size = 0.2, stratify = y_train, random_state = 42)</pre><ul><li><em>stratify</em> will make sure that the distribution of classes in train and test / validation set is similar.</li><li><em>random state</em> to regenerate the same train and validation set.</li><li><em>test size</em> 0.2 will keep 20% data in validation and remaining 80% in train set.</li></ul><p><strong>DEFINING ARCHITECTURE OF MODEL: </strong>I would recommend before using the optimizers and activation functions while defining the architecture of the model kindly let us understand from the following blogs about optimizers and various activation functions.</p><ul><li><a href="https://medium.com/analytics-vidhya/optimizer-loss-functions-in-neural-network-2520c244cc22">Optimizer &amp; Loss Functions In Neural Network</a></li><li><a href="https://medium.com/analytics-vidhya/activation-functions-in-neural-network-55d1afb5397a">Activation Functions In Neural Network</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*AvPUl_qWBJq4FCZMFJwrPA.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>Here, we will be defining the nos. of input, hidden and output neuron.</p><pre># Creating a skeleton of model.<br>from keras.models import Sequential</pre><pre># Defining layers<br>from keras.layers import Input, Dense</pre><p>Defining input, hidden, output neurons and architecture. For now, I have picked <strong><em>relu</em></strong> as an activation function for hidden layers. Also, since it is a binary classification problem, I have used <strong><em>sigmoid</em></strong> activation function in the final layer. There is no hard and fast rule that we have to use these activation functions only. We can can other activation functions as well.</p><pre># Input neurons<br>input_neurons = X_train.shape[1]</pre><pre># Output neurons (Since it is binary classification)<br>output_neurons = 1</pre><pre># Defining hidden layers &amp; neurons in each layersnumber_of_hidden_layers = 2<br>neuron_hidden_layer_1         = 10<br>neuron_hidden_layer_2         = 5</pre><pre># Defining the architecture of the model<br>model = Sequential()<br>model.add(InputLayer(input_shape=(input_neurons)))<br>model.add(Dense(units=neuron_hidden_layer_1, activation=&#39;relu&#39;))<br>model.add(Dense(units=neuron_hidden_layer_2, activation=&#39;relu&#39;))<br>model.add(Dense(units=output_neurons, activation=&#39;sigmoid&#39;))</pre><p><strong>COMPILING THE MODEL (LOSS FUNCTION / OPTIMIZER): </strong>In this part we define our loss function and optimizer which is helpful in validating our data and backward propagation.</p><pre>model.compile(loss=&#39;binary_crossentropy&#39;,optimizer=&#39;Adam&#39;,metrics=[&#39;accuracy&#39;])</pre><p><strong>TRAINING THE MODEL: </strong>In this part we will train our model by passing our independent and dependent variable along with validation data and nos. of epochs which specifies the nos. of times our model is going through the training set.</p><p>For each of the epoch, there will be a loss generated for the training and validation set and also we will get the accuracy for training and validation set since we have defined them during compilation phase and we are capturing</p><pre>model_history = model.fit(X_train, y_train, validation_data = (X_test, y_test), epochs = 50)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KhaIT95b3rSzm8VRl_EmMw.png" /></figure><p><strong>EVALUATING MODEL ON TEST DATA: </strong>Here, we will predict the classes for our data and use metric as <em>accuracy </em>to evaluate models performance.</p><pre># Getting predictions for the test set<br>prediction = model.predict_classes(X_test)</pre><pre># Getting accuracy score<br>from sklearn.metrics import accuracy_score<br>print(&quot;Accuracy_Score : {}&quot;.format(accuracy_score(prediction, y_test) * 100))</pre><p>After predicting classes on test and validation data, we got descent accuracy of 80% on both.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LOn7RBSnp26mKn-ERqVxNA.png" /></figure><p><strong>VISUALZING RESULTS (LOSS &amp; ACCURACY): </strong>Here, we will see the variation in loss function and accuracy observed over nos. of epochs.</p><ol><li>LOSS FUNCTION</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mFbTfapdZySHUxWlAlDnoA.png" /></figure><p>In the above figure we can see that as the nos. of epochs increases the loss decreases. After certain nos. of epochs the validation loss does not seems to be improving.</p><p>2. ACCURACY</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-KG-jjp0ZuSRTbjCN_zJ8g.png" /></figure><p>As we can see accuracy for 5 to 10 epochs did not change much. After that the accuracy started to improve for both training and validation set so we can say that model started learning. From epoch 20 to 100 there was slight improvement or we can say that model stopped learning.</p><p>So, that’s how we build a neural network model on a data set. I hope you enjoyed it.</p><p><strong>CONCLUSION</strong></p><p>So, in this blog we have learnt how to solve a simple neural network on loan prediction problem using ANN. We can further improvised the model’s performance by doing various hyper parameter tuning and observing it’s accuracy on random data.</p><p>Do connect with me on LinkedIn : <a href="https://www.linkedin.com/in/gaurav-rajpal/">https://www.linkedin.com/in/gaurav-rajpal/</a></p><p><strong><em>Stay tuned for further updates on demo projects where we play with image dataset in Convolution Neural Network and see Transfer Learning.</em></strong></p><p><strong><em>If you liked it pleas give 50 applauses.</em></strong></p><p>Regards,</p><p>Gaurav Rajpal (gauravrajpal1994@gmail.com)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdac5e945fcc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/simple-loan-prediction-project-using-neural-network-bdac5e945fcc">Simple Loan Prediction Project using Neural Network.</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tensorflow-GPU Installation with CUDA & CuDNN]]></title>
            <link>https://medium.com/analytics-vidhya/tensorflow-gpu-installation-with-cuda-cudnn-40fbd4477e7?source=rss-a26b76928645------2</link>
            <guid isPermaLink="false">https://medium.com/p/40fbd4477e7</guid>
            <category><![CDATA[cudnn]]></category>
            <category><![CDATA[cuda]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[knowledge-sharing]]></category>
            <dc:creator><![CDATA[Gaurav Rajpal]]></dc:creator>
            <pubDate>Sat, 31 Oct 2020 14:38:57 GMT</pubDate>
            <atom:updated>2020-11-02T16:13:28.016Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bp9W7seIgx8flRLL" /><figcaption>Source: Internet</figcaption></figure><h3>What is a Tensorflow ?</h3><p>Tensorflow is a software library or framework, designed by the Google team to implement machine learning and deep learning concepts in the easiest manner. It combines the computational algebra of optimization techniques for easy calculation of many mathematical expressions.</p><p>This is a official website of TensorFlow : <a href="https://www.tensorflow.org/">www.tensorflow.org</a></p><p>Let us now consider the following important features of TensorFlow:</p><ul><li>It includes a feature of that defines, optimizes and calculates mathematical expressions easily with the help of multi-dimensional arrays called tensors.</li><li>It includes a programming support of deep neural networks and machine learning techniques.</li><li>It includes a high scalable feature of computation with various data sets.</li><li>TensorFlow uses GPU computing, automating management. It also includes a unique feature of optimization of same memory and the data used.</li></ul><h3>Why is TensorFlow So Popular?</h3><p>TensorFlow is well-documented and includes plenty of machine learning libraries. It offers a few important functionalities and methods for the same.</p><p>TensorFlow is also called a “Google” product. It includes a variety of machine learning and deep learning algorithms. TensorFlow can train and run deep neural networks for handwritten digit classification, image recognition, word embedding and creation of various sequence models.</p><h3>TensorFlow GPU Installation:</h3><p><a href="https://www.tensorflow.org/install/source">Build from source | TensorFlow</a></p><blockquote><strong>Step 1: Install Anaconda framework</strong></blockquote><p>Before we install TensorFlow, we need to install <a href="https://www.anaconda.com/products/individual">Anaconda framework</a> in our system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1AJg46oC4Zyb4i99.png" /></figure><p>After successful installation of anaconda, check in command prompt through “conda” command. Then execute the following command to create a virtual environment through the anaconda prompt the installation of TensorFlow .After successful environmental setup, it is important to activate TensorFlow module.</p><p>conda create — name tensorflow python = 3.6.9(python version should be greater than 3.5)</p><p>conda activate tensorflow</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*d41hYKlY51gXwkBk.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*INeeyWpacHIHCssD.png" /></figure><p>this article below assumes that you have a CUDA-compatible GPU already installed on your PC</p><blockquote><strong>Step 2: Check the software you will need to install</strong></blockquote><p>Assuming that Windows is already installed on your PC, the additional bits of software you will install as part of these steps are:-</p><ul><li>Microsoft Visual Studio</li><li>the NVIDIA CUDA Toolkit</li><li>NVIDIA cuDNN</li><li>Tensorflow (with GPU support)</li></ul><blockquote><strong>Step 3: Download Microsoft Visual Studio 2017</strong></blockquote><p>Visual Studio is a Prerequisite for CUDA Toolkit because from this we are taking all the prerequisite C++ ibraries(Desktop development with C++,Mobile development with C++). There are different different version available of visual studio code but we have to download <a href="https://visualstudio.microsoft.com/vs/older-downloads/">Visual Studio Community Version 2017</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Fnh3gWkZ7jeYs7Z-.png" /></figure><p>After installing the Microsoft visual studio you will get this type of interface you have to select few libraries of C++ and go for installation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4DDWElSltLAXIFyD.png" /></figure><p>If you attempt to download and install CUDA Toolkit for Windows without having first installed Visual Studio, you get the message shown in Fig.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/0*NMpFoBOEdNqXB4NC.png" /></figure><blockquote><strong>Step 4: Download CUDA Toolkit for Windows</strong></blockquote><p>These CUDA installation steps are loosely based on the<a href="https://docs.nvidia.com/cuda/cuda-installation-guide-microsoft-windows/index.html"> Nvidia CUDA installation guide for windows</a>. The CUDA Toolkit (free) can be downloaded from the Nvidia website <a href="http://developer.nvidia.com/cuda-downloads">here</a>.</p><p>At the time of writing, the default version of CUDA Toolkit offered is version 11.1. However, you should check which version of CUDA Toolkit support in your system(Just run in your command prompt navidia-smi) .When you go onto the <a href="https://www.tensorflow.org/install/gpu">Tensorflow website</a>, the latest version of Tensorflow requires CUDA 10.2, not CUDA 11.1.</p><p>CUDA site will show the latest(currently v11.1) to download. Please make sure Tensorflow requires CUDA 10.2. You can download CUDA 10.2 from <a href="https://developer.nvidia.com/rdp/assets/cudnn-8.0-windows10-x64-v5.0-ga-zip">here</a>. You need to sign up to download the older version.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*twqFxLMOqOqse_BY.png" /></figure><p>just go with exe[local]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/0*3lBLz4EqkdaMw1mr.png" /></figure><p>The CUDA installer extracts to your PC and, when complete, the NVIDIA CUDA Toolkit installation will start; you will get a message to that effect. The resulting NVIDIA Installer windows throughout the installation process are shown at Figs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/0*S3ksg_i0eey0X-rL.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/0*uIFjKST9NGTDyX7z.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/0*ll9qafzNawVwLAit.png" /></figure><p>Pressing ‘next’ at the window shown in Fig. above, gives the final installation window, shown as Fig.13 below, where the NVIDIA installer is marked as finished.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/0*F0gfM4LVEpEnMi1I.png" /></figure><blockquote><strong>Step 5: Download and Install cuDNN</strong></blockquote><p>Having installed CUDA 10.2 base installer and its four patches, the next step is to find a compatible version of CuDNN. Based on the information on the Tensorflow website, Tensorflow with GPU support requires a cuDNN version of 8.0.4.</p><p><strong>1.Downloading cuDNN</strong></p><p>In order to <a href="https://developer.nvidia.com/cudnn">download CuDNN</a>, you have to register to become a member of the NVIDIA Developer Program (which is free).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hV02uoARyDL4kd8j.png" /></figure><p>Fig Creating a free membership account in order to download cuDNN</p><p>When you create an account, login and fill out some other required details about why you are using the account, you get the download page shown in Fig.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iHgA0Ih8tVKN2krq.png" /></figure><p>As I have downloaded CUDA 10.2, the corresponding version of cuDNN is version 8.0.4. Choosing cuDNN version 8.0.4 enables the download as a zip file named as follows:</p><p>cudnn-10.2-windows10-x64-v7.zip</p><p><strong>2. Unzipping cuDNN files and copying to CUDA folders</strong></p><p>Instructions <a href="https://docs.nvidia.com/deeplearning/sdk/cudnn-install/index.html#install-windows">at Nvidia</a> provide support for windows cuDNN installation, as do instructions on the Tensorflow website ; I have reproduced these instructions in distilled form, based on my implementation of them. In my case, I downloaded the cuDNN .zip file .</p><p>Unzipped the cuDNN “.zip” file where I downloaded it, hence the unzipped folder structure which will contain the required cuDNN files is now:-</p><p>There are three files in the unzipped cuDNN folder subdirectories which are to be copied into the CUDA Toolkit directories. These are cudnn64_7.dll, cudnn.h and :</p><p><strong><em>1. cudnn64_7.dll</em></strong></p><p>cudnn64_7.dll can be found in the following path within the downloaded cuDNN files:</p><p>&lt;downloadpath&gt;\cudnn-10.2-windows10-x64-v7.5.0.56\cuda\bin\cudnn64_7.dll</p><p>Assuming that you installed CUDA 10.2 to its default path namely the following default path:</p><p>C:\Program Files\NVIDA GPU Computing Toolkit\CUDA\v10.2</p><p>you can copy the cudnn64_7.dll file directly into the CUDA folder’s bin folder path (note: you don’t need to create any new subfolders):</p><p>C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.2\bin\</p><p><strong><em>2. cudnn.h</em></strong></p><p>As with the cudnn64_7.dll file above, after downloading and unzipping the cuDNN folder, the header file cudnn64.h can be found in the path:</p><p>&lt;downloadpath&gt;\cudnn-10.2-windows10-x64-v7.5.0.56\cuda\ include\cudnn.h</p><p>Again, assuming that you installed CUDA 10.2 into the default path , copy cudnn.h directly into the CUDA folder with the following path (no new subfolders are necessary):</p><p>C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.2\include\</p><p><strong><em>3. cudnn.lib</em></strong></p><p>The .lib file cudnn.lib can be found in the downloaded cuDNN path:</p><p>&lt;downloadpath&gt;\cudnn-10.2-windows10-x64-v7.5.0.56\cuda\lib\x64\cudnn.lib</p><p>Copy cudnn.lib directly into the CUDA folder with the following path:</p><p>C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.2\lib\x64\</p><p>Step 5.3: Checking CUDA environment variables are set in Windows</p><p>Finally, the <a href="https://docs.nvidia.com/deeplearning/sdk/cudnn-install/index.html#install-windows">instructions at Nvidia</a> direct that you ensure that the CUDA environment variable has previously been set up, as follows:</p><p>Variable Name: CUDA_PATH<br>Variable Value: C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.2</p><p>In Windows 10, the Environment Variables can be found by choosing:</p><p>Control Panel -&gt;System and Security-&gt;System-&gt;Advanced System settings.</p><p>This opens up a window called “System Properties” (Fig 17), at which point the “Environment Variables” button should be chosen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/0*RRHQs6x73G64sXRU.png" /></figure><p>Environment Variables button (in System Properties window) for setting and checking CUDA paths</p><p>When the Environment Variables window then appears, within “system variables” (in the bottom half of the window), click on “Path” and choose the button “edit”. A new window will appear, called “Edit environment variable” as shown in Fig below.</p><p>On checking the Environment Variables, I found the installation process which determines the CUDA installation path had already added two paths to CUDA . These paths are shown in Fig below, so I found I did not need to add a further CUDA path.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/0*7dzypUs8_nWZ1eLG.png" /></figure><blockquote><strong>Step 6: Install Tensorflow with GPU support</strong></blockquote><p>To install gpu version of tensorflow just type pip install tensorflow-gpu(in my case i have used tensorflow-gpu==2.0.0 vesion) command over your anaconda prompt(in virtual envionment) i.e. in our case tensorflow(as you can see step 1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FMLsu7UqR3tJU3u8.png" /></figure><blockquote><strong>Step 7: Test Installation of TensorFlow and its access to GPU</strong></blockquote><p>To check your tensorflow installation just type importing the tensorflow package<br>import tensorflow as tf over your Anaconda command prompt .</p><p>Also please running following commands to check if GPU is installed or not.</p><p><a href="https://nbviewer.jupyter.org/github/grajpal123/GPU_TESTING/blob/main/GPU%20-%20TEST.ipynb">Notebook on nbviewer</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40fbd4477e7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/tensorflow-gpu-installation-with-cuda-cudnn-40fbd4477e7">Tensorflow-GPU Installation with CUDA &amp; CuDNN</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Image Classification Using ANN.]]></title>
            <link>https://medium.com/analytics-vidhya/image-classification-using-ann-c524f36d22c?source=rss-a26b76928645------2</link>
            <guid isPermaLink="false">https://medium.com/p/c524f36d22c</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[analytics-vidhya]]></category>
            <category><![CDATA[knowledge-sharing]]></category>
            <dc:creator><![CDATA[Gaurav Rajpal]]></dc:creator>
            <pubDate>Wed, 14 Oct 2020 06:06:01 GMT</pubDate>
            <atom:updated>2020-10-14T12:51:56.545Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*li67MIk1Myyguh1phLzPaQ.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>In this blog we will be doing a project based on image classification where our problem statement describe us to classifies the images into two categories i.e. Emergency &amp; Non-Emergency vehicle which is a binary classification problem and we will be solving using neural network.</p><p>Before diving deep into this project I would recommend you all to please go through the basics of working with images in my deep learning blog. I am sure you will like it and then proceed ahead with exciting theory and practical&#39;s coming ahead.</p><p><a href="https://medium.com/analytics-vidhya/getting-started-with-image-data-deep-learning-328faad6d929">Getting Started with Image Data — Deep Learning</a></p><p>Coming to emergency vehicles there can various types like <strong><em>police cars, ambulance or even fire trucks.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*f_zmIPXlQJS3t1XxKnKOOg.png" /><figcaption>Source: Analytics Vidhya (Emergency Vehicle)</figcaption></figure><p>Any other vehicle which does not belong to police cars, ambulance and firetrucks come under the category of Non-Emergency vehicle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZshJXoN8aqNP64WNbh8g_w.png" /><figcaption>Source: Analytics Vidhya (Non-Emergency Vehicle)</figcaption></figure><p><strong>STEPS TO SOLVE PROBELM.</strong></p><ol><li><em>Loading the data</em>.</li><li><em>Creating training, validation and test data</em>: We will train on train data and evaluate on validation data and test on test data.</li><li><em>Defining the architecture of our model</em>: We will define how many input neurons, nos. of neurons in hidden layer and output layer.</li><li><em>Compile the model (loss function / optimizers)</em>: Here we will be defining our cost function which will be used during backward propagation.</li><li><em>Train the model: </em>We will train our model and define nos. of epochs.</li><li><em>Evaluate models performance on training and validation data</em>.</li></ol><p><strong>VIEWING DATASET: </strong>We have dataset in a form of csv file and below we see the first five rows of it. The first column represent the image name and the corresponding column will tell us whether the image is an emergency vehicle or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*mCalp-0bCoHmZzH6nXQLUQ.png" /><figcaption>Source: Analytics Vidhya.</figcaption></figure><p>You all can hit up at my GitHub profile to download the code file and dataset where I have implemented the classification problem.</p><p><a href="https://github.com/grajpal123/Emergency_Non-Emergency_Vehicle_Image_Classification/tree/main">grajpal123/Emergency_Non-Emergency_Vehicle_Image_Classification</a></p><p>If you are just interested to look at the implementation part please visit the following URL where you all have to not take the pain of downloading the code file or the dataset.</p><p><a href="https://nbviewer.jupyter.org/github/grajpal123/Emergency_Non-Emergency_Vehicle_Image_Classification/blob/main/EMERGENCY%20vs%20NON-EMERGENCY%20IMAGE%20CLASSIFICATION.ipynb">Notebook on nbviewer</a></p><p>So, I would believe that if you would have gone through the implementation you would have clearly seen that, we have done a lot of hyperparameter tuning and could achieve an accuracy of 78% better than our previous implementation where we had got an accuracy of 76%. We also focused on reducing the False Negative (FN) by various hyperparameter tuning.</p><p>Now, we will be looking at how we can improvise our existing model which we have build.</p><h4><strong>IMPROVING DEEP LEARNING MODEL / NEURAL NETWORK.</strong></h4><p>Here we will be looking at the techniques which can be used to improve our deep learning model. We will be applying those techniques on our Emergency vs Non-Emergency classification problem and compare the performances.</p><ol><li><strong>EARLY STOPPING.</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bIU9dCav9b3rA_hGEsFkfA.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>Above figure represents the loss graph vs nos. of epochs. Here blue line shows training loss and orange lines shows validation loss. On x-axis we have epochs and on y-axis we loss.</p><p>If we consider nos. of epochs between 0–20 we see that both the training and validation loss are decreasing. Initially they both have high loss value and as the training progresses i.e. as the nos. of epochs increases their loss value decreases. Also the amount by which they are reducing is similar. So, we can say that they are in sink. With increasing in the nos. of epochs beyond 20 we observe that training loss is decreasing whereas the validation loss seems to be either increasing or remain same. This portion where training loss is decreasing and validation loss is either increasing or remaining constant is called as <strong><em>Overfitting. </em></strong>In this scenario,<strong><em> </em></strong>model seems to memorize the training data and avoids learning signals from the data. We don’t want this situation to happen. If we achieve some method it will help to perform well on validation data or unseen data.</p><p>To solve the above problem what we can do is to stop the training of the model at a point where it starts to overfit or memorize the training data and this technique is called as <strong><em>Early-Stopping. </em></strong>This method will help to generalize the model well on unseen data. <strong><em>By applying early-stopping, we can stop the training of the model once the validation loss starts decreasing .</em></strong></p><p>By using early-stopping we need to keep a track of metric like <em>validation loss or validation accuracy. </em>Another parameter is<em> threshold </em>(if loss is not decreasing by certain threshold value). Last is <em>nos. of epochs </em>(if loss has not decrease over certain nos. of epochs we will stop the training process).</p><p>Consider eg. threshold = 0.01 &amp; nos. of epochs = 5. if we selected these parameters, the training will stop when the validation loss has not decreased by 0.01 over 5 successive epochs. These are the parameters which we have to consider while using early stopping method and we have to be very care full while choosing these parameters and see it that it does not leads to overfitting again.</p><p>Let us see where does early stopping round fits in our normal steps to solve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5cZxrI5-JMVccCEN5yWdKQ.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>Let us look at the practical implementation of early stopping:</p><p><a href="https://nbviewer.jupyter.org/github/grajpal123/Emergency_Non-Emergency_Vehicle_Image_Classification/blob/main/Early_Stopping.ipynb">Notebook on nbviewer</a></p><p>2. <strong>DROPOUT REGULARIZATION.</strong></p><p>We discussed one of the problem with neural network i.e. after certain nos. of epochs model starts to overfit and how we can resolve it by using early stopping previously. Early stopping is just one method to prevent overfitting.</p><p>Let us try to find out the reasons of overfitting first and then we will come to another solution of overfitting.</p><ul><li>Does not learn patterns / signals from training data.</li><li>Model starts to memorize the training data.</li></ul><p>Here, comes the another method to prevent overfitting i.e. <strong><em>Dropout Regularization.</em></strong></p><p>Recalling back our architecture of neural networks were we saw hidden layers are responsible for creating features and some of them might lead to overfitting because of memorizing the training data so, what dropout does is that, it drops some of the neurons from hidden layer and ensures that none of the neurons are dependent on some of the specific features.</p><p>Let us understand it more clearly. Dropout assigns the probability to each of the hidden layers on which we wish to apply drop out. This probability denotes a chance whether the neuron will be dropped or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vftHvUr3wqDVPvkoYJZMvg.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p><strong>How does it helps to overcome overfitting ?</strong></p><p>Without dropout it might be possible that a particular neuron from hidden layer would be influenced by only a particular feature which leads to overfitting since our model is now memorizing the training set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*ZsKpSTua-TQSqOOQACgGMg.png" /><figcaption>Source: Analytic Vidhya (Without Dropout)</figcaption></figure><p>Thus, <strong><em>dropout makes sure that the output of any one neuron in not dependent on any one feature</em></strong>. In dropout, when we randomly drop the neurons from the hidden layers in each iteration we will see, we have different set of neurons which makes sure that no neurons are memorizing the inputs or getting influenced by some feature.</p><p><strong>KEY POINTS TO REMEMBER:</strong></p><ul><li>Neurons are dropped randomly at each iteration.</li><li>Generally, we don’t apply dropout on the input layer.</li><li>No dropout during testing.</li></ul><p>Let us see where does dropout fits in our normal steps to solve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*igWwycLdp71Xg4hM3cltJw.png" /></figure><p>Let us look at the practical implementation of drop out.</p><p><a href="https://nbviewer.jupyter.org/github/grajpal123/Emergency_Non-Emergency_Vehicle_Image_Classification/blob/main/Dropout_in_Neural_Networks_using_Keras.ipynb">Notebook on nbviewer</a></p><p>3. <strong>BATCH NORMALIZATION.</strong></p><p>The technique what we will be discussing here is most frequently used by deep learning practitioners and it generally works almost every time i.e. <strong><em>Batch Normalization.</em></strong></p><p>Consider below neural network,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bsTD2Nm5MXnnxJZBOsKJDA.png" /></figure><p>Here,</p><ul><li>X1,X2, X3,X4 represent nos. of features.</li><li>W1,W2,W3,W4. . . Wn represent the weights.</li><li>Consider bias = 0 simplicity sake.</li><li>Activation function = sigmoid.</li></ul><p>If we recall, we normalize the inputs before sending them to the model which helps to speed up the training process. Using this normalize value we perform forward propagation and proceed ahead in calculate the activation function of hidden layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0PpuvoGrTmmPocgN3nwk4A.png" /></figure><p>Consider the above figure,</p><p>If we see in the figure, inputs were normalize but as we compute hidden layer activations by performing dot product which means the values are not normalize so, it would be great if these activation function which we are applying on hidden layer are also normalize. So, imagine if these activation values are normalized we would be achieving great results and less training time would be taken by our model to converge. <strong><em>Batch Normalization help us to achieve this task.</em></strong></p><p><strong>How the batch normalization happen ?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PHlA9n5DRTujA-nF2Ku3Tw.png" /><figcaption>Source: Analytics Vidhya.</figcaption></figure><ul><li>We calculate the mean of all the activations of particular layer.</li><li>Next we take the standard deviation</li><li>Once we have mean and std. we normalize the values, where we substract mean from activation values and divide by std. and add a very less value called <em>epsilon</em> to make sure denominator is not 0. This makes the mean and std. of all hidden layer activations 0 and 1 respectively.</li></ul><p>Let us see where does batch normalization fits in our normal steps to solve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yrvv5g7bDcdXiVYZZD7JqA.png" /></figure><p>Also in practical session we saw using batch normalization our model converge faster and achieved better accuracy in less nos. of epochs.</p><p><strong>What are the advantages of using Batch Normalization ?</strong></p><ul><li>Batch normalization speeds up the training process by normalization of hidden layer activation.</li><li>Smoothens the loss function / cost function.</li></ul><p>Let us look at the practical implementation of the batch normalization.</p><p><a href="https://github.com/grajpal123/Emergency_Non-Emergency_Vehicle_Image_Classification/blob/main/Batch_Normalization_in_Neural_Networks_using_Keras.ipynb">grajpal123/Emergency_Non-Emergency_Vehicle_Image_Classification</a></p><p>4. <strong>IMAGE AUGMENTATAION</strong>.</p><p><strong>Why do we need Image Augmentation ?</strong></p><p><strong><em>Image Augmentation</em></strong><em> is basically altering the existing data in order to create more data for the model in training process.</em></p><p>A deep learning model works well when it has huge amount of data. More the data better is the performance of the model. But acquiring massive amount of data comes with its own challenges. Every time we won’t be having large amount of data to feed the network.</p><p>If we recall in the emergency and non-emergency classification we had just 2300 images. Also, it becomes too expensive to collect the data which might result into shortage of the data because of which our deep learning model cannot learn patterns from the data hence it might not give good performance. So, in this case <strong><em>Image Augmentation</em></strong> comes into picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g8PzAsq61z1deHNoOjSIlA.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>Instead of spending days manually collecting the data, we can use image augmentation technique which generates new images from original image. With image augmentation we have not collect our data manually. Also, it increases the nos. of training samples.</p><p>Consider the below figure where we have original image form training data on left hand side and remaining are the samples of the image obtained form image augmentation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fnwJfLo5TLfkOSZ14xHFzw.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p><strong>IMAGE AUGMENTATION TECHNIQUES.</strong></p><ol><li><em>Image Rotation</em>: This is one of the most commonly used technique. Even if we rotate the image, the information of image remains same. Eg. A cat is cat even if we see it from different angle.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*Ww_SVB_FKE3Yu2rmtzKxgw.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>2. <em>Image Shifting</em>: If we are using this technique, we can change the position of the object in an image and hence give more variety to the model which can lead to more generalize model. It is basically geometric transformation that maps the positions of every object in an image to a new location in the final image. An object presented on location (x,y) in the input image is shifted to a new position (X, Y), where X = x + dx, Y = x + dy. Here dx and dy are respective shifts along different directions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*pdZVTuA-v1961yigV_5R1w.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>3. <em>Image Flipping</em>: Flipping can be considered as an extension of rotation. It allows us to flip an image in left-right direction or up-down direction. The left most image is original image from training set and other two images are flipped images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*vFTUDR7H2qTwQI8f7RnYOA.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>4. <em>Image Noising</em>: It is another popular technique where we add noise to the image which basically helps our model to separate the signals from noise in an image. This makes our model more robust to changes in an input image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*NHEl9QCLTCyxZ7tuL8sC7Q.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>5. <em>Image Blurring</em>: Images comes from different sources. Some might be high quality image where as some might be low quality image. In such cases we can blur the original high quality image and this will make our model more robust to changes in the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*CDbqMA6qS7loqLB6l88BQg.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>Let us look at the practical implementation of image augmentation.</p><p><a href="https://github.com/grajpal123/Emergency_Non-Emergency_Vehicle_Image_Classification/blob/main/Image_Augmentation_Techniques.ipynb">grajpal123/Emergency_Non-Emergency_Vehicle_Image_Classification</a></p><p>5. <strong>MODEL CHECKPOINTING.</strong></p><p>This technique is another important technique which is used while building our neural network model. It has following advantages:</p><ul><li><strong>It saves the best model for us during the training process</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*h0Cm5B2TWCjfwzN2RYBLmw.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>In the above fig. while making the predictions the weights and biases stored during the last epochs will be used. So, the model will train till specified nos. of epochs which is 50 in our case and parameter learnt during the last epoch will be used to make the predictions. But, if we look closely at the figure the best validation loss is achieved at epoch nos. 45.</p><p>Let us look at the model history to understand it more clearly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PJh4HteB8My7Dsdu9epsCw.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>So, through model checkpointing instead of saving the last model or the parameters of last epoch we are going to save the model which produces best result and this model is called as best model.</p><ul><li><strong>In case of system failure, we wont lose much information since model is being saved constantly.</strong></li></ul><p>So, after understanding the intuition behind the model checkpointing we must be wondering how does it saves the best model. So, to answer that in keras we define 2 parameters i.e. <em>monitor &amp; mode.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*Qey_JyEwXLHAwUqUlgUWqg.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>Let us look at the practical implementation of the model checkpointing.</p><p><a href="https://github.com/grajpal123/Emergency_Non-Emergency_Vehicle_Image_Classification/blob/main/Model%20Checkpointing%20in%20Keras.ipynb">grajpal123/Emergency_Non-Emergency_Vehicle_Image_Classification</a></p><p>So, these are techniques which can be used for improving our deep learning model. Let us combine all of them and see the performance of our model.</p><p>Following is the practical implementation link. You can hit up at my GitHub profile for code &amp; dataset for this part. Please refer <strong><em>EMERGENCY vs NON-EMERGENCY — MODIFIED VERSION.ipynb.</em></strong></p><p><a href="https://github.com/grajpal123/Emergency_Non-Emergency_Vehicle_Image_Classification">grajpal123/Emergency_Non-Emergency_Vehicle_Image_Classification</a></p><p>Also, if you are just interested to look at the demo of this part please visit the below.</p><p><a href="https://nbviewer.jupyter.org/github/grajpal123/Emergency_Non-Emergency_Vehicle_Image_Classification/blob/main/EMERGENCY%20vs%20NON-EMERGENCY%20-%20MODIFIED%20VERSION.ipynb">Notebook on nbviewer</a></p><p><strong>CONCLUSION</strong></p><p>So, in this blog we have learnt how to solve an image classification problem using artificial neural network. We also saw various improvising techniques like <em>early stopping , dropout, batch normalization, model checkpointing</em> which can used to improve our deep learning model. Lastly, we combined all the techniques and saw the performance of our model.</p><p>Do connect with me on LinkedIn : <a href="https://www.linkedin.com/in/gaurav-rajpal/">https://www.linkedin.com/in/gaurav-rajpal/</a></p><p><strong><em>Stay tuned for further updates on demo projects where we play with image dataset in Convolution Neural Network.</em></strong></p><p>Regards,</p><p>Gaurav Rajpal (gauravrajpal1994@gmail.com)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c524f36d22c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/image-classification-using-ann-c524f36d22c">Image Classification Using ANN.</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Image Data — Deep Learning]]></title>
            <link>https://medium.com/analytics-vidhya/getting-started-with-image-data-deep-learning-328faad6d929?source=rss-a26b76928645------2</link>
            <guid isPermaLink="false">https://medium.com/p/328faad6d929</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[analytics-vidhya]]></category>
            <category><![CDATA[knowledge-sharing]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Gaurav Rajpal]]></dc:creator>
            <pubDate>Tue, 06 Oct 2020 09:10:03 GMT</pubDate>
            <atom:updated>2020-10-07T16:35:12.747Z</atom:updated>
            <content:encoded><![CDATA[<h3>Getting Started with Image Data-Deep Learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*LhjsYYzSyrn4LHD4hcp5xA.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>In this blog we will be studying about how Deep Learning techniques can be applied to study about unstructured data like images or text. Our main focus or agenda in this blog will be to understand what are images and how we can work with image data. So, lets start our journey.</p><h4>INTRODUCTION TO IMAGE DATASET :</h4><p>Ever imagined how are images stored in the dataset. If not, let us see how are the images stored in a computer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*Q-Q451uK1-6UXXchLuEXbg.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>Consider a black &amp; white or grey scale image. This is an image of number 8. Now if we keep zooming it we will see image is getting distorted and we will see small squares on the image. Now these are called as <strong>pixels. </strong>Also we use the term dimension of the image is X x Y which means nos. of pixels across height and width. Although we see the image in this format, the computer stores it in form of numbers where each of pixels are denoted as numerical value and this numerical value denotes the intensity of the pixel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XugjC4nuQbpPRO8J8mGS4Q.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>For grey-scale image intensity ranges from 0–255. Value closer to 0 represent darker shade where as value closer to 255 represent lighter shade. <strong><em>So, every image in a computer is stored in a form of matrix of numbers and this matrix is also known as a channel.</em></strong></p><p>Let us now look at the colored image how they are been stored in a computer. Consider following colored image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ku_tUqgEU-MuUQUDybfJxA.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>Now the image is composed of many colors and almost all colors can be generated from 3 primary colors — <strong><em>red, green, blue. </em></strong>So, we can say that each colored image is composed of 3 colors or 3 channels which means in colored image nos. of channels will be more.</p><p>In the particular example we have 3 matrixes or channel — R, G and B. Now each of this matrix will have values ranging from 0 to 255. Finally all these channels are superimposed so the shape of the image when loaded in the computer will be N x M x 3 where N represent the nos. of pixels across height, M represents the pixels across width and 3 represent nos. of channels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PwuMzg2JEAtCYlOQm-fjYg.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>So these were the two most popular formats <em>Grey-Scale</em> &amp; <em>RGB format. </em>Let us look at them in more detail and explore other image formats.</p><h4>DIFFERENT IMAGE FORMATS :</h4><p>There are different types of image dataset we will be coming across to work with. Some of them are as follows.</p><ol><li>Greyscale Images.</li><li>RGB Images.</li><li>RGBA Images.</li><li>MRI Images.</li></ol><blockquote><strong>Greyscale Images</strong>: Here are the examples of some of the grey scale images which we are familiar before as well.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*LY42rzHqvgxOLUrug7hE5g.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><blockquote><strong>RGB Image: </strong>Here are the examples of some of the RGB images.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*tv54zj-gXhSc_-I8GmMNrQ.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><blockquote><strong>RGBA Image</strong> : Here are the example of some of the RGBA images.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*23bQWd94Q1LmH7UDvhRz8A.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>Let us understand the difference between above image. First image (starting from left) is perfectly clear. Second image has slightly faded colors. In third image colors are barely visible.</p><p>Similar to RGB format, RGBA image is stored as a 3D matrix where shape of matrix is N x M x channels. In case of RGBA images we will be having 4 channels and the fourth channel is called as <strong>alpha channel </strong>where alpha controls opacity or transparency of the colors. The range of alpha value is between (0–255) where 0 is transparent and 255 is completely the original image. If the value is between 0–255 image is partially opaque depending upon the pixel intensity.</p><p>Here are the few examples,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*C4zM47Qkf8Re5VHAbdmWFw.png" /></figure><p><em>For alpha = 10, image is completely occluded.</em></p><p><em>For alpha = 150, which is somewhere between 0–255 we can see colors are partially visible so we can say it is partially opaque.</em></p><p><em>For alpha = 200, which very close to 255 and hence the colors are visible in this case hence image is shown as it is.</em></p><blockquote><strong>MRI Images : </strong>They are stored as 4D matrix where shape of matrix is given as follows — <strong>N x M x slice x channel.</strong></blockquote><p>Consider an image of brain and as we know brain will be a 3D object so from this image we can see just the outer structure of the brain. In order to capture internal sections of the brain, we create multiple slices of the brain and capture each of these and later stack them to create a 4D matrix . Some popular places where we will find these type of images are CT Scan and MRI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*Xw_H9DPaD9x3LbKmqH2fhg.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>Now after having a brief understanding over different types of the images we will now look at few examples for each of the formats discussed via jupyter notebook.</p><p>Not to make the article very long so, I have posted the jupyter notebook where I have performed the practical’s related to what we have studied so far.</p><h4>I would highly recommend you all to go through the jupyter notebook link which you all can see under each part and understand the practical’s as well. You will really enjoy it. So, why are we waiting let us begin.</h4><blockquote><strong>PART 1 — READING &amp; STACKING IMAGE.</strong></blockquote><p>In this lab session I have covered about various formats of the image. How we can read an image, how to view them using popular python package <strong><em>skimage</em> </strong>and how to display multiple images of same format using <strong><em>glob</em> </strong>by reducing nos. of lines of code. Also, to work with MRI images you will come across a popular library which I have used i.e. <strong><em>nibabel.</em></strong></p><p>You can hit up at my GitHub link for code &amp; images file for this part <a href="https://github.com/grajpal123/Reading_Stacking_Images_DL"><strong><em>Reading_Stacking_Images_DL</em></strong></a></p><p>Also, if you are just interested to look at the demo of this part please visit the below link. <a href="https://nbviewer.jupyter.org/github/grajpal123/Reading_Stacking_Images_DL/blob/main/READING%20%26%20STACKING%20IMAGES%20.ipynb"><strong><em>Reading_Stacking_Images_DL</em></strong></a></p><blockquote><strong>PART 2 — CONVERTING IMAGE TO DIFFERENT FORMATS.</strong></blockquote><p>In this lab session I have covered the recap of different types of images and how we can convert from one format into another format. <strong>Also we must understand that converting an image from lower to higher quality is extremely difficult like converting GRAY-SCALE into RGB.</strong></p><p>You can hit up at my GitHub link for code &amp; images file for this part <a href="https://github.com/grajpal123/Converting_Images_DL"><strong><em>Converting_Images_DL</em></strong></a></p><p>Also, if you are just interested for demo of this part please visit the below link <a href="https://nbviewer.jupyter.org/github/grajpal123/Converting_Images_DL/blob/main/CONVERTING%20IMAGES%20-%20DIFFERENT%20FORMAT.ipynb"><strong><em>Converting_Images_DL</em></strong></a></p><blockquote><strong>PART 3 — EXTRACTING EDGES FROM IMAGES.</strong></blockquote><p>In this lab session we will be talking about how to extract the edges from the image. Also, we will see two types of filter i.e. <strong><em>Sobel &amp; Prewitt</em></strong>.</p><p>But, before jumping into the practical’s let us understand why edges are important. Consider that you are given a task to classify whether an object is a person, car or an animal from a bunch of an image. We can easily classify them looking at the size and shape quite simple right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*2y1fYzZBGh07RmrJsHnBFQ.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>Now, let us change the example a bit. If we do so, we will still be able to classify them a bit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*TGOofJSWOjMiIUxpi-JDSg.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>The main difference between two of them is that — In the second case we remove the color, background and other minute details. We only had the edges and we were still able to identify the objects in an image. So, for any given image if we are able to extract only the edges and remove the noise, we will still be able to classify the object in an image.</p><p>Consider the following example,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*YbdSrZI4ucGcw9ydjMW06w.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>We will clearly observe that in the above example, the pixel values around the edges shows a sudden change from left to right or from top to bottom. So, based on this fact we can identify that which pixel represent the edge or which pixel lie on the edge.</p><p>We compare the pixel value with it’s surrounding pixel value to determine if that if it represents an edge. For eg.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*FHB31eHKRcysj_Tbk-mMJA.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>We can use a matrix to perform element wise multiplication to determine if a particular pixel is an edge or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*Tf9Nv-umdsF6EGV0u-GOnw.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>In the above example as the pixel value comes out to be less after applying the matrix so, we can say that it can lie on the edge but it does not represents an edge.</p><p>Let us consider another example,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*dKc-BGymapHcRu_JCe0xpQ.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>In the above example as the pixel value comes out to be very large after applying the matrix we can clearly say that the highlighted pixel values represents an edge.</p><p>Now this matrix which we saw in the above examples is called as a <strong><em>filter</em></strong> or <strong><em>kernel. </em></strong>This kernel or the filter slides across the whole image to generate a new matrix. This new matrix is called as a <strong><em>feature map </em></strong>and this feature map denotes whether the pixel lies on the edge or not.</p><p><strong>TYPES OF KERNEL :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*t0OmuJ5SojtEB7EeKo-v_A.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>The main difference between Sobel &amp; Prewitt filter is that in Sobel filter high importance is given to the pixel values right next to the target pixel where as in Prewitt it is not.</p><p>You can hit up at my GitHub link for code &amp; images file for this part <a href="https://github.com/grajpal123/Extracting_Edges_DL"><strong><em>Extracting_Edges_DL</em></strong></a></p><p>Also, if you are just interested for demo of this part please visit the below link <a href="https://nbviewer.jupyter.org/github/grajpal123/Extracting_Edges_DL/blob/main/EXTRACTING%20EDGES.ipynb"><strong><em>Extracting_Edges_DL</em></strong></a></p><p><strong>CONCLUSION</strong></p><p>So, in this blog we learnt about various formats of the image like RGB, RGBA, MRI and GRAY-SCALE image. We also had brief discussion about the dimensions of them. We also saw how we can convert one format of an image into another and came across a new library <strong><em>nibabel </em></strong>to work with MRI and CT scan type of images. Lastly we studied about various types of kernel i.e. <strong><em>Prewitt &amp; Sobel </em></strong>which helps us to extract the edge features in an object and helps us to reduce the noise in the background<strong><em> </em></strong>thus reducing the computational power.</p><p>Do connect with me on LinkedIn : <a href="https://www.linkedin.com/in/gaurav-rajpal/">https://www.linkedin.com/in/gaurav-rajpal/</a></p><p><strong><em>Stay tuned for further updates on demo projects where we play with image dataset in Deep Learning.</em></strong></p><p>Regards,</p><p>Gaurav Rajpal (gauravrajpal1994@gmail.com)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=328faad6d929" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/getting-started-with-image-data-deep-learning-328faad6d929">Getting Started with Image Data — Deep Learning</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizer & Loss Functions In Neural Network]]></title>
            <link>https://medium.com/analytics-vidhya/optimizer-loss-functions-in-neural-network-2520c244cc22?source=rss-a26b76928645------2</link>
            <guid isPermaLink="false">https://medium.com/p/2520c244cc22</guid>
            <category><![CDATA[knowledge-sharing]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[analytics-vidhya]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Gaurav Rajpal]]></dc:creator>
            <pubDate>Sat, 03 Oct 2020 14:48:05 GMT</pubDate>
            <atom:updated>2020-10-05T12:44:42.103Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*uSruGL2Nf3p8pipSFIjN7g.png" /><figcaption>Source: Internet</figcaption></figure><p>In this blog we will understand about the various optimizers and loss functions which are most commonly used while training our neural networks. The prerequisite for this is to have basic understanding of how gradient descent algorithm works so, I would highly recommend you all to refer my previous blog on <a href="https://medium.com/@gauravrajpal1994/introduction-to-neural-networks-1d111bb4649"><strong><em>Introduction To Neural Network</em></strong></a> for better understanding over Gradient Descent algorithm which is used during the backward propagation for updating our weights and minimize the cost function where our aim is to reach the global minima.</p><p>After having gone through the basics of gradient descent algorithm we will look at the following things:</p><ol><li>Variants of Gradient Descent.</li></ol><p>2. Challenges / Problems with Gradient Descent.</p><p>3. Different types of optimizers.</p><p>Let us recall the gradient descent equation which is: <strong>w = w - alpha * dE/dw </strong>where<strong>, dE/dw</strong> represents rate of change of error with respect to weights and <strong>alpha</strong> represents the learning rate. Here <strong>‘E’ </strong>is the cost function.</p><p>There are multiple ways to calculate this cost functions. Based on the way we are calculating this cost function there are different variance of gradient descent. Lets us understand it in a better way.</p><p><strong>VARIANTS OF GRADIENT DESCENT.</strong></p><p><strong>BATCH GRADIENT DESCENT</strong> : Let us say there are total ‘m’ observations in our dataset and we are using all of these observation to calculate cost function ‘E’. So, we are taking entire training set, performing forward propagation and calculating the cost function. Then we update the parameters what we call as weights with rate of change of this cost function with weights. Also we must remember that, as we are using the entire training set over here, parameters will be updated only once per epoch.</p><p><strong>STOCHASTIC GRADIENT DESCENT </strong>: If we are using single observation to calculate the cost function it is called as stochastic gradient descent commonly abbreviated as SGD. Here each iteration is taken passed it through neural network calculate the error and then update the parameters. Then we will take the second observation and perform similar steps. This process keeps of going for the number of the observations in our dataset. So for 1 epoch we will be having ‘m’ updations, where ‘m’ represents the number of observations in our dataset.</p><p><strong>MINI BATCH GRADIENT DESCENT : </strong>In this type of gradient descent we take a subset from the entire training dataset and calculate the cost function. This type of gradient descent is used mostly while training deep learning model.</p><p><em>Let us see the variation of the cost functions </em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*arl0S6cRXR6TlSueDg5PcA.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>Coming to batch gradient descent as we are taking the entire dataset the cost function reduces smoothly. Coming to SGD it is not that smooth, since we are updating the parameters based on single observation so there are lot of iterations involved. It can also be possible that model starts to learn noise as well. Updation of cost function in case of min-batch gradient descent is smoother as compared SGD since we are not updating the parameters after every iterations but after every subset of the data.</p><p><em>Let us see the computation cost and time:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F3VNpZsjIEgCm_VgurezOA.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>We can see that mini-batch gradient descent gives better result than others and is also used most often while building deep learning models.</p><p>So, these are the variants of gradient descent which we discussed and you will come across these quite often. Hope now you are well versed with the terms??</p><p>Let us now jump to the challenges what we face when we are using the gradient descent.</p><p><strong>CHALLENGES OF GRADIENT DESCENT</strong> .</p><p>In this part we will focus on the challenges of gradient descent. Let us take a look at it.</p><ol><li><strong>It get stuck at local minima (SGD Momentum)</strong></li></ol><p>Let us say below is the graph of our cost function. Since we want to minimize the cost we would like to reach ‘<strong>Global Minimum</strong> - The point which has minimum cost value in the entire cost function or globally is known as global minima.” The lowest point among its neighbors is called as <strong>Local Minima. </strong>This is the point where the gradient descent generally gets stuck.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*aJyrtHPKD2dNmxKe--BE2w.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>Using the gradient descent algorithm we will calculate the slope at each and every point and after some point reach local minima. The slope at local minima is 0 so dE/dw term becomes 0 which represent the gradient or slope because of which parameters will not get updated and will get stuck .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*sADj-NdraYbNZtnmZpwwjg.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>Our aim is not to reach local minima, our aim is to reach global minima. So, we require some push at the local minima which takes us out from this scenario.</p><p>Let us understand this with an example:</p><p>Consider we have a ball at certain height with initial speed as ‘u’ . Now the ball rolls down the hill or slope with some speed say ‘v’ , We can obviously say that v &gt; u since ball is rolling down. When the ball reaches the local minima it would have gained some speed which will eventually give it a push and ball will come out of local minima. So, we saw to push the ball out of local minima we need some accumulative speed kind of thing. In terms of neural network we can say that the accumulative speed is equivalent to weighted gradients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*i3DsPE7DK1FvMUXfeFQSZQ.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>Here if we see local minima, the slope or the gradient will be 0 which will eventually make current gradient at current time ‘t’ equal to 0. We will still be left with some value i.e. previously accumulated gradient at ‘t-1&#39; and hence the weighted gradient ‘Vt’ will have some value which will give the require push and it will come out of local minima. The ‘beta’ value tells us how much value it should give to current and previously accumulated gradient. Generally beta value is taken as 0.9 which means it will give 10% weightage to current gradient and 90% weightage to previously accumulated gradient. Now ‘Vt’ being our new gradient will be used to update the parameters of neural network. <strong><em>This is also know as Stochastic Gradient Descent with Momentum.</em></strong></p><p>So, using the concept of Stochastic Gradient Descent with Momentum we can solve the problem of getting stuck at local minima.</p><p><strong>2. Same learning rate throughout the training process. (RMSProp)</strong></p><p>This is the second issue which we will encounter while training our neural network. In general it might be possible that some variables will lead to faster convergence as compared to other variables but if we apply same learning rate throughout the training phase, we are enforcing them to be in sync. This might lead to slower convergence.</p><p>Our aim is that when the training progress, learning rate should also be updated as per the cost function. Let us see how we can get this resolved.</p><p>Going back to our gradient descent equation where dE/dw is the gradient which gets updated during our training process, so we can use this term for updating the learning rate. <strong>There is some issue with it, as some gradients might be positive or negative at some point so they might cancel each other so, to remove the sign we can take sum of squares of gradients and use this value to update the learning rate.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*jmwtAA6PzJMTgfvxOnqUbQ.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>There can be another issue with this approach i.e. <em>The square of any number be it negative or positive will always be a positive number so, adding all the positive numbers will always increase the theta value and in return it will reduce the learning rate and after some iterations learning rate will tend to zero and become very small and our parameters will be almost similar to previous parameters which will lead to slower convergence.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*WlI-ROvf69_G9lAUeFE5Aw.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>To overcome this issue we can use SGD with momentum equation which assigns some magnitude to our current gradient and previously accumulated gradients and we will take a square of our gradients to nullify the effect of negative values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*wo0D-waf1phfBEMoNOwepA.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>This is updated equation of RMSProp. As we can see from the above equation we are using alpha which is divided by square root of weighted average plus some small error. The error is used in the denominator so that the value does not becomes 0. Generally this error value is very small i.e. 0.00000001.</p><p>Now let us understand how this equation helps us to update the learning rate during the training process- <em>When the square of gradients is high, weighted average value will be high which in return reduce the learning rate. Similarly when square of gradients is low, weighted average value will low which in return increases the learning rate.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*bkY6_QXHuqGXCFpEiONpKw.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p><strong>DIFFERENT TYPES OF OPTIMIZERS.</strong></p><ol><li>Stochastic Gradient Descent with Momentum.</li><li>RMSProp.</li><li>ADAM.</li></ol><p>Till now we have covered two optimizers which was discussed in the above section to overcome the challenges faced while using gradient descent. In <strong>SGD with momentum</strong> we saw it resolved the issue of getting stuck at local minima using the weighted sum of previously accumulated gradient. In <strong>RMSProp </strong>we saw that it resolved the problem of same learning rate for all the parameters using sum of square gradients.</p><p>Now, we will look at the most commonly and widely used optimizer i.e. <strong>ADAM. </strong>It combines both SGD with momentum to resolve local minima problem and RMSProp which uses sum of square of previous gradients to resolve same learning rate issue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*gqOtPQVk1vYiWKPCo3vKVg.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>From the updated equation of ADAM, we can see that we are using ‘Vt’ here as the gradient which is the weighted sum of current and previously accumulated gradients to resolve the local minima issue also the square root of the sum of squares of gradient resolves the same learning rate issue.</p><h4>So, this was the detailed intuition behind the various types of optimizers which are used in building our neural network. I hope you enjoyed learning it.</h4><h3>LOSS FUNCTIONS:</h3><p>In this section we will learn about what are loss functions and which of them are mostly used in deep learning.</p><p>Before looking at the loss function, lets recap about the neural network a bit. If we see the below figure, we will come to know how are our predictions been calculated and error function helping us to update the weights and biases in the neural network which helps us to improving the predictions and performance of the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qUz_Iqy2c02qth0MTkH3dw.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><ol><li><strong>MEAN SQUARED ERROR: </strong>Until now we were using MSE (Mean Square Error) to calculate the error / loss function / cost function. Let us see how we can calculate MSE.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CXl-l9aU0qps30W1hrHJOA.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p><em>MSE is generally used when we have regression type of problem and target variable is continuous.</em></p><p><strong>2. MEAN ABSOLUTE ERROR: </strong>MAE is another metric which is used to calculate the loss function. Let us see how we can calculate MAE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*ZNAyobakZk_Kjh7EQr_NXA.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p><em>MAE is also used when we have regression type of problem and target variable is continuous.</em></p><p><strong>3. ROOT MEAN SQUARED ERROR: </strong>RMSE is just the square root of MSE. We know how to calculate MSE so in RMSE we will just calculate the square root of the value obtained.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*Ds2E4l9xQbzDMwEWlbS1Eg.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>So, until now we saw some of the loss functions for the regression task. Lets us now look at the loss functions used for classification task.</p><p>Classification task can be further divided into <strong>binary classification</strong> and <strong>multiclass classification. </strong>In binary classification we only 2 target classes in our target variable where as in multiclass classification we can have more than 2 classes in target variable to predict. Let us understand the loss function used in both:</p><p><strong>1. BINARY CROSS ENTROPY / LOG LOSS.</strong></p><p><em>“It is the negative average of the log of corrected predicted probabilities”</em></p><p>It is most common type of loss function used for classification problem. It compares each of the predicted probabilities to the actual class output which can wither be 0 or 1. It then calculates the scores which penalizes the probabilities based on the distances with actual value.</p><p>Let us understand what are the corrected probabilities with an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*ky6EsvK4qtdmPe0KPxbvgQ.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>Here, we see corrected probabilities column against each observation. We have predicted probabilities column which comprises the probabilities of class 1. For actual values as 0, predicted probabilities represent the probability of class 1 so, the probability that it belongs to class 0 would be obtained by subtracting the value from 1. This would be happen for ID8, ID2 and ID5 in our example.</p><p>So, we take the corrected probabilities belonging to target class 1 as it is and for the probabilities where actual target is 0, we subtract the predicted probability from 1. We then take log of these corrected probabilities as taking log will give less penalty for small differences (for eg. if actual is 1 and predicted probability is 0.9 we assign less penalty, if actual is 1 and predicted is 0.6 we assign little higher).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*ghpeOlnkm210O4UmfJGhlw.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>Instead of calculating the corrected probability, we can use the formula that is written below. Suppose the actual class is 1, (1-y) term will 0. Similarly if actual class is 0, y*log(p) term becomes 0</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*hSrIlvXeHWa58_T4ZASu9w.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>So, this is how we calculate binary cross entropy and it is very useful loss function used for classification problems.</p><p><strong>CONCLUSION</strong></p><p>So, we learnt about various optimizer like Stochastic Gradient Descent which resolve the issue of local minima, RMSProp which resolves the issue of same learning rate and then we learnt about ADAM which was the combination of both. Then we learn about various loss functions which can be used in regression and classification problem.</p><p>Do connect with me on LinkedIn : <a href="https://www.linkedin.com/in/gaurav-rajpal/">https://www.linkedin.com/in/gaurav-rajpal/</a></p><p><strong><em>Stay tuned for further updates on demo projects where we play with image dataset in Deep Learning.</em></strong></p><p>Regards,</p><p>Gaurav Rajpal (gauravrajpal1994@gmail.com)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2520c244cc22" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/optimizer-loss-functions-in-neural-network-2520c244cc22">Optimizer &amp; Loss Functions In Neural Network</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Activation Functions In Neural Network]]></title>
            <link>https://medium.com/analytics-vidhya/activation-functions-in-neural-network-55d1afb5397a?source=rss-a26b76928645------2</link>
            <guid isPermaLink="false">https://medium.com/p/55d1afb5397a</guid>
            <category><![CDATA[knowledge-sharing]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[analytics-vidhya]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[activation-functions]]></category>
            <dc:creator><![CDATA[Gaurav Rajpal]]></dc:creator>
            <pubDate>Thu, 01 Oct 2020 09:31:12 GMT</pubDate>
            <atom:updated>2020-10-05T12:45:31.736Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*TEhut1cV5r63K6LbvdoaaQ.png" /><figcaption>Source: Internet</figcaption></figure><p>In this blog we will learn about the activation function which are most widely used in Deep Learning. Before jumping to the point lets recap in short about the basic architecture of neural network and understand it’s working in short.</p><p>For simplicity purpose consider the multilayer perceptron.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*OKOUfaFz7QyRIc_ncwK4VQ.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>We had set of inputs. These inputs where send to hidden layer and we calculated the Z value which was multiplication of input features and some weights. After this operation we used activation function to calculate output H. We used sigmoid activation function on Z. The results where then sent to next layer where we had some weights and bias and we then calculated output O.</p><p>For more detail you can refer my previous blog for better understanding <a href="https://medium.com/@gauravrajpal1994/introduction-to-neural-networks-1d111bb4649">https://medium.com/@gauravrajpal1994/introduction-to-neural-networks-1d111bb4649</a></p><p><strong>The question arises why do we need activation function at all. To resolve this question lets understand it better.</strong></p><p>One main reason is that it could not capture the complex relationship within the data. Also, we would be left with just linear combination of inputs and weights along with bias.</p><p>Let us visualize using <a href="https://playground.tensorflow.org/#activation=tanh&amp;batchSize=10&amp;dataset=circle&amp;regDataset=reg-plane&amp;learningRate=0.03&amp;regularizationRate=0&amp;noise=0&amp;networkShape=4,2&amp;seed=0.79089&amp;showTestData=false&amp;discretize=false&amp;percTrainData=50&amp;x=true&amp;y=true&amp;xTimesY=false&amp;xSquared=false&amp;ySquared=false&amp;cosX=false&amp;sinX=false&amp;cosY=false&amp;sinY=false&amp;collectStats=false&amp;problem=classification&amp;initZero=false&amp;hideText=false">TensorFlow Playground</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*oepbfGO75-o38M8pZD4AgQ.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>In the TensorFlow Playground we can see on left we have multiple data options. In middle we have our architecture defined. We have inputs X1 and X2 and single hidden layer and then output layer. We can also see an option to change activation function, learning rate etc. <strong>The objective is to create a decision boundary that separates orange points from blue points</strong>. So, lets see after having activation function as <strong>linear</strong> what was the result.</p><p>We will observe in the figure that in less than 100 epochs it could create best decision boundary for the simple dataset which we had chosen, and train and test set loss was 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*OpUKY2YWJy4se-pAQQu1KA.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>Let us now select another dataset in Tensor Flow Playground where decision boundary is not that easy to create. It is circular one and later while training the model using linear activation function we will see that we cannot derive at the best decision boundary which separates the orange and blue points even after more number of epochs and no improvement in train and test loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*jpKEsaYfcMEYeI8fMl03-Q.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>Now let us visualize the decision boundary when we select sigmoid activation function keeping everything the same.</p><p>We will see that model is able to train well and able to classify the two types of data points properly in less than 200 epochs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*3FVDpAgRNJxDWgP4exfpAQ.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>So, changing the activation function from linear to sigmoid added non-linearity in the network which made the network strong enough to capture the relationship within the data. Hope now the use of activation function is clear among you guys?</p><p>Now, since you are aware about the importance of activation function lets dig dive into the types of the activation functions used in Deep Learning.</p><h3><strong>TYPES OF ACTIVATION FUNCTION.</strong></h3><blockquote><strong><em>LINEAR ACTIVATION FUNCTION</em></strong></blockquote><p>Linear activation function is the simplest activation function. It does not capture any non-linearity in the data as we observed earlier.</p><p>The mathematical equation for linear activation function is <strong>y = ax </strong>which says that for any input x, output will be a times of x.</p><p>Consider a = 1, the graph will be looking like,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DMa3bPxLr2IlHu-uL2MsLw.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>Based on the above result observed we can say that the input can be any value ranging from (- infinity, + infinity) same goes with output. This is one of the condition for activation function to be continuous.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lTs_qotQ3cGXBPN9VHwpMQ.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>Second condition of activation function which says that, “It should be differentiable at every point.” . Let us look at derivative of linear activation function. We will see when we take derivative w.r.t x we will get co-efficient of x i.e. a.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*t8-YFEu1A88TXfFv9OCIJQ.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>This is the simplest activation function and does not capture the non-relationship within the data. This function is often used at the output layer of regression problem. Consider the example where we need to predict the income based age, experience and qualification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fh1SBMHfwsese_8Tb2HAyw.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><blockquote><strong><em>SIGMOID ACTIVATION FUNCTION</em></strong></blockquote><p>It is most of the popular used activation function and we have used it earlier as well to demonstrate how it is useful in capturing non-linearity in the data via Tensor Flow Playground.</p><p>The mathematical equation of sigmoid activation function is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tdZ0WxV0l_Mf6tuU6SA4Cw.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>The best part of sigmoid activation function is that it restricts the output values between 0 and 1. The values are generally treated as probabilities and hence sigmoid function is generally used at the output layer where we need to calculate the probability of the classes. Also, from the graph above we can see that sigmoid activation function is continuous and differentiable at each and every point.</p><p>Let us look at the derivative of SIGMOID activation function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6keYuNcx5Yzg9t6R7eOArQ.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>From the above plot we can see that the curve is quite flat which means that the gradient or the derivative value of this activation function will be quite small.</p><p>For better understanding of the steps how we arrived at the derivative of sigmoid activation function you all can refer the link below.</p><p><a href="https://towardsdatascience.com/derivative-of-the-sigmoid-function-536880cf918e">Derivative of the Sigmoid function</a></p><blockquote><strong><em>TANH ACTIVATION FUNCTION</em></strong></blockquote><p>TANH activation function is quite similar to sigmoid activation function. We can say it is scaled version of sigmoid activation function.</p><p>The mathematical equation of tanh activation function is as follows :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1019/1*thTErTk4QOMHgNrqHoAuvg.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>In tanh activation function the output values are between (-1, 1) where as in sigmoid activation function we saw the output values range from (0,1).</p><p><strong><em>DIFFERENCE BETWEEN SIGMOID &amp; TANH</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*K6CPOphICfaNiVDMiyElCg.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>From the graph above we can see tanh function is steeper at the center around 0. Also this graph makes it clear that <strong>TANH is scaled version of SIGMOID.</strong></p><p>Let us look at the derivative of the TANH activation function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*KEMiN1powp_MwhVc9MFTSw.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>Compared to sigmoid activation function, the values of tanh activation function are comparatively larger. Hence training is faster in terms of tanh as the gradient values will be larger and updating weights would be faster.</p><blockquote><strong><em>ReLU ACTIVATION FUNCTION</em></strong></blockquote><p>ReLU stands for <strong>Re</strong>ctified <strong>L</strong>iner <strong>U</strong>nit. It is one of the most commonly used activation function in deep learning.</p><p>This function returns 0 for all the negative values and for any value greater than 0 the function returns the same output. Lets look at the equation below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DnObHoLfQtWCi7PcG4VeMw.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>We can see that for all the values greater than 0 it acts like a linear function and can also be represented as max(0, x), where x is any real number. Also it is clear that any negative input values of weights the result would be 0 that means neurons are not activated in forward propagation process. Since only certain number of neurons are activated ReLU activation function is computationally effective as compared to sigmoid and tanh activation function.</p><p><strong><em>DIFFERENCE BETWEEN ReLU, TANH &amp; SIGMOID</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*jVaURy8esAAxqDUCF-RTlQ.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>Going back to the <strong>TANH</strong> and <strong>SIGMOID</strong> activation function we saw that they both are differentiable at each and every point but coming to <strong>ReLU</strong> activation function, we see that it is not differentiable at point x = 0.</p><p>Let us look at the derivative of ReLU activation function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*oedpnKPI6EEZTuL9RNvUEQ.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>As we see for all the value greater than 0 it’s value of derivative is 1 and for values less than 0 it is 0. It’s derivative is not defined at value x=0.</p><p><strong>For implementation purposes the value of derivative at x=0 is considered to be 0.</strong></p><p>There is still one such problem with this function. The derivation of some neurons still becomes 0 hence some of the weights and bias are not updated. So to resolve this issue we have another activation function.</p><blockquote><strong><em>LEAKY ReLU ACTIVATION FUNCTION</em></strong></blockquote><p>Leaky ReLU is an activation function which overcomes the disadvantage encountered in ReLU layer i.e. the derivation of some neurons becoming 0. To resolve this issue it returns a small value 0.01 of x for x &lt; 0 instead of 0.</p><p>Let us look at equation below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*imxPwL1ljaowN2tW0OWMaw.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>Lets look at the derivative of Leaky ReLU activation function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*90WHKzgXQHNvIOvut3UrnQ.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>So, when we calculate the derivative of leaky relu activation function it will be 0.01 for all values of x ≤ 0 and 1 for all values of x &gt; 0.</p><blockquote><strong><em>SOFTMAX ACTIVATION FUNCTION</em></strong></blockquote><p>SoftMax activation is generally used for multiclass classification.</p><p>Before jumping into as to why this activation function is used for multiclass classification let us first understand what exactly is multiclass classification problem. For eg:</p><p>Consider below figure, for each observation we have 5 features and target variable has 3 classes (Class 1, Class 2 and Class 3)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*9rdT2CSUqg5ucVKEZhutPw.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>Let us create simple neural network for the problem discussed above. We will see we have 5 input features in the input layer. Next we have 1 hidden layer which has 4 neurons. Obviously we can increase the number of neurons and number of layers in the architecture but for now we are considering only neuron with 4 hidden layer. Each of these neurons use input, weights and bias to calculate the value Z represented by Zij (1st neuron of 1st layer, we call it Z11 and so on). Over these values we apply activation functions and send the result to output layer.</p><p>Now can you guess the number of neurons in the output layer ???</p><p>If you guessed it, 3 you were right as we were having 3 classes in our target variable of our data set. Each of the individual neuron will give you the probability of individual classes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*yDdvv7UcP3djBF7qti2wgQ.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>In the above figure, we can see that 1st neuron in the output layer will give us the probability of it belonging to Class 1 . Similarly 2nd neuron will give us the probability of it belonging to Class 2 and finally 3rd neuron will give us the probability of it belonging to Class 3.</p><p>Now, suppose we calculate the Z value using the weights and bias of the output layer and apply sigmoid activation function knowing that sigmoid activation function gives us the value between 0 and 1, we will get some output values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*tpXiQHlPaUhHvXheGBGLjw.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>If we think deeper , we can see that we will encounter 2 problem in this case. First, if we apply the threshold = 0.5, It will say us that the input layer belongs to 2 classes (Class 1: 0.84 and Class 2: 0.67). Secondly , the probability values are independent of each other (probability that the data point belongs to class 1 does not take into account probability of other 2 classes).</p><p><strong><em>This is the reason why SIGMOID activation function is not preferred for multiclass classification problem. So instead of SIGMOID we use SOFTMAX activation function.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*RYyFDAvEOF1FvcsTUYA7XQ.png" /></figure><p>Using the SoftMax activation we can get the relative probabilities which means that it uses the probabilities values of multiple classes in the target to calculate the final output.</p><p>Let us see how does SoftMax activation function works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*URTTd_Lxrz8eX2C8MvqsmQ.png" /><figcaption>Source: Internet</figcaption></figure><p>SoftMax function turns logits [2.0, 1.0, 0.1] into probabilities [0.7, 0.2, 0.1], and the probabilities sum to 1.</p><p><em>In deep learning, the term logits layer is popularly used for the last neuron layer of neural network for classification task which produces raw prediction values as real numbers ranging from [-infinity, +infinity ]. — Wikipedia</em></p><p>SoftMax turn <em>logits</em> (numeric output of the last linear layer of a multi-class classification neural network) into probabilities by take the exponents of each output and then normalize each number by the sum of those exponents so the entire output vector adds up to one.</p><p>Let us consider step wise what happens basically (Assumption):</p><p><strong>STEP 1: Assume we got following values for output layer.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*J3veqhZXDbkFyuLOCoLEEA.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p><strong>STEP 2: Applying SoftMax activation function to each of these neurons.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*EFtt_6fhL1CO9_hPxk94lw.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>We must note that, these are the probability values for the input data point belonging to the respective classes. We must note that sum of the probabilities in these case is 1. So in this case it is clear that the input belongs to class 1. Also if the probability values of any classes change, probability value for class 1 will also change.</p><p>This is all about SOFTMAX activation function. Hope you understood it ?</p><h3>HOW TO CHOOSE ACTIVATION FUNCTION FOR OUR NEURAL NETWORK ?</h3><p>You guys may be wondering that up till now we have studied the various activation function and looked at their mathematical equations and derivatives, understood the terminology as to why they are useful. In this part we will explore which activation function we can use for our neural network.</p><ol><li><strong>Linear Activation Function</strong></li></ol><p>It is used in for <strong>REGRESSION </strong>type of problem at output layer where the target variable is continuous. As we already discussed linear activation function cannot capture non linearity in the data hence it is preferred to have it at output layer while we can use non-linear functions like RELU and TANH over the hidden layer.</p><p>2. <strong>Sigmoid Activation Function</strong></p><p>As we already know it returns values between 0 and 1 which are treated as probabilities of output classes. Generally it is use for <strong>BINARY CLASSIFICATION PROBLEM </strong>while we can use other activation function at the hidden layer.</p><p>3. <strong>ReLU &amp; TanH Activation Function</strong></p><p>These activation functions are popularly used for <strong>HIDDEN LAYERS</strong> of the neural network. Infact ReLU activation function has shown to be performed better than other activation function and is the popular choice.</p><p>4. <strong>Softmax Activation Function</strong></p><p>Similar to sigmoid activation function, softmax activation function returns the probabilities of each class and is used at the output layer and most frequently used in <strong>MULTICLASS CLASSIFICATON.</strong></p><p>CONCLUSION</p><p>This bring to the end of our topic of discussion. Hope you enjoyed it and liked exploring the theoretical concept behind activation function used in Deep Learning. If so please please like it and give it a clap.</p><p>Do connect with me on LinkedIn : <a href="https://www.linkedin.com/in/gaurav-rajpal/">https://www.linkedin.com/in/gaurav-rajpal/</a></p><p><strong><em>Stay tuned for further updates on Optimizers / Loss Functions and demo projects on Deep Learning.</em></strong></p><p>Regards,</p><p>Gaurav Rajpal (gauravrajpal1994@gmail.com)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55d1afb5397a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/activation-functions-in-neural-network-55d1afb5397a">Activation Functions In Neural Network</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction To Neural Networks]]></title>
            <link>https://medium.com/analytics-vidhya/introduction-to-neural-networks-1d111bb4649?source=rss-a26b76928645------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d111bb4649</guid>
            <category><![CDATA[analytics-vidhya]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Gaurav Rajpal]]></dc:creator>
            <pubDate>Tue, 29 Sep 2020 08:04:13 GMT</pubDate>
            <atom:updated>2020-10-06T08:52:15.371Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction To Neural Networks.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*waEpRHnSgvmj2ItG1XTWsA.png" /><figcaption>Source: Internet</figcaption></figure><p>In this article we will be learning about following things.</p><ol><li>Perceptron.</li><li>Bias and Weights concepts in neuron.</li><li>Basic difference between step and sigmoid function.</li><li>Multilayer perceptron.</li><li>Forward and Backward Propagation.</li><li>Gradient Descent</li></ol><p>So why are we waiting lets dig dive and understand the concepts behind all the above terms used in Neural Network.</p><blockquote><strong>PERCEPTRON</strong></blockquote><p><strong><em>“A neuron with step function as the activation function is a perceptron” . </em></strong>Let us understand with following example.</p><p><strong>INTRODUCTION: WHAT IS NEURON ?</strong></p><p>Let us start with simple example of classification problem — Loan Prediction. Our aim is to approve loan or not based on the salary of the person. To do that we will have to build a model that takes salary as an input and predicts if loan should be approved or not.</p><p>Suppose your bank wants to reduce the loan of risk default and hence decides to roll out loans to only those people who have salary greater than 50,000 per month and above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*aX9jCPD7SPt2jQ6CZ7OLMA.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>The task involved for our model are as follows:</p><p>1. Take salary as input.</p><p>2. Check if salary is &gt; 50,000 or not.</p><p>3. If condition is true only then output a “Yes”.</p><p>The above steps are like what is happening in a biological neuron which takes the input through dendrites, process the input and produces the output. Thus, model which we are talking about can also be called as a neuron.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*Jx6hCLCbMaWHdP8GS1qD0Q.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><blockquote><strong>BIAS &amp; WEIGTHS CONCEPT:</strong></blockquote><p><strong>WHAT IS BIAS?</strong></p><p>Coming to our loan example lets look at each of the inputs closely. In general, we can have Applicant Salary, Father’s Salary, Spouse Salary that can be deciding factor to approve the loan. Our neuron will take all these features as an input and make decision which is similar to multiple dendrites which we saw in biological neuron. We can sum up all the income and check if total income crosses the threshold (benchmark) set by the bank. If it is based on previous history, we can approve loan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*CLFE3M5xeN7qBYucJCOfaA.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>Now if we bring threshold to left hand side of the equation it will look something like below,</p><p><strong><em>X1 + X2 + X3 — threshold &gt; 0</em></strong></p><p>If we replace the threshold with a new term bias the updated equation would look like summation of 4 quantities where bias is the threshold.</p><p><strong><em>X1 + X2 + X3 + bias &gt; 0</em></strong></p><p>Here, bias which is set by us arbitrarily is learned by the underlined data. If input exceeds the magnitude of the bias we want the neuron to give output as ‘Yes’. This event is known as <strong><em>Firing of Neuron.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*vyQ3HbExuZ1zN9hRGmGTCA.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>If we want to write above relationship using equations we will say,</p><p><strong><em>If X1 + X2 + X3 + bias &gt; 0 then output should be 1</em></strong></p><p><strong><em>If X1 + X2 + X3 + bias &lt;= 0 then output should be 0</em></strong></p><p>Consider the equation: Z = X1 + X2 +X3 +bias, Output will be 1 if (X1 + X2 +X3 +bias &gt; 0), else 0. This is called as a<strong><em> Step Function i.e. step(Z). </em></strong>This step function is basically used to scale the outputs of our neuron. In deep learning we have an option to choose these step functions to apply to output of the neuron. These are called as <strong><em>Activation Functions.</em></strong></p><p>So, when we use step function as an activation function for our neuron is called as a <strong>PERCEPTRON. </strong>Hope the definition of perceptron make’s it clear now to you all ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*knON6LNFUhwwUStnYjdxTg.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p><strong>WHAT ARE WEIGHTS IN PERCEPTRON ?</strong></p><p>In previous example how we saw neuron takes sum of all inputs along with bias and decide if loan should be approved or not. It means that each feature was given same importance. We can also denote this in following manner where 1’s on input neuron connection represent the weights given to input feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*XmH6czs06iWUBwMMHZ6ZlA.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>Let’s take following example to understand it in a better way. To calculate output Z in this case we will multiple each input feature with its corresponding weights and finally add them with bias.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*TCKY5p44VSiB2wkAjdz0mg.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>As we see in above example all input features are given equal weights. Ideally applicant salary plays a vital role so it should be given more weights. So, considering that scenario we can consider the below example where applicant salary has been given more weightage as compared to father’s and spouse salary. We will calculate output Z and check if it is greater than 0 or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*xxWKot0MpGz2NKibxFbEnA.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>In above example as the output Z was greater than 0 there are high chances that the loan will be getting approved.</p><p>Now that you have an intuition or understanding how a neuron works, lets formalize the learning through math. First, we take input and multiple it by their weights. Second, we add a bias to this value. The final value is represented as Z. Once we have value of Z we use it in step function to convert it to either 1 or 0 based on which Z is positive or negative which becomes the final output of the neuron.</p><p><strong><em>We should note that until now we where taking weights and bias arbitrarily, but these are learned during the training process.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*-MDmtHvySpQ_ux83sRrZ-w.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><blockquote><strong>DIFFERENCE BETWEEN STEP &amp; SIGMOID FUNCTION:</strong></blockquote><p>In step activation function we have values either 0 or 1 whereas in sigmoid function we can see from the graph that it is continuous function which can return any value between 0 and 1 (0.2, 0.7, 0.6 etc.) These values can be treated as probabilities. Higher the probabilities imply higher the chance that loan will be getting approved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*4J0-30ZLW88EljXm06IaGQ.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>If we change the activation function of the perceptron from step to sigmoid function, we will get the Logistic Regression model as we are using sigmoid function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*Yag4f127Mz4X6ytNxirbCg.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><blockquote><strong>MULTILAYER PERCEPTRON:</strong></blockquote><p>In multilayer neuron. Instead of single neuron we have two neurons which would assign some weights to our input features. Also, there would be some bias associated with these neurons. Lets us take some example for better understanding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*jz_CggbsURT7QvGWBL87nA.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>In above example we see that 1st neuron has given more weight to applicant income whereas 2nd neuron has given less importance to it and it is more focus on family’s income by giving high weightage to father and spouse salary. In other words, these neurons are creating new features from existing features in the data. This happens during entire training process. Remember in ML we had to create our own features, here DL model creates features on its own. Once we have F1 and F2 we apply activation function over these results. To calculate the final output, we can add one more neuron. This neuron will also have some weights and bias associated with it. This is called as a <strong>MULTILAYER PERCEPTRON.</strong></p><p>Consider following architecture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*OKOUfaFz7QyRIc_ncwK4VQ.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>We have 2 layers. Layer 1 is called as <strong>HIDDEN LAYER</strong> which performs all mathematical calculation to generate features and Layer 2 is called the <strong>OUTPUT LAYER</strong>. Number of neurons in the output layer will depend upon the number of the classes in the target. Since we are focusing on Loan Prediction, which is binary classification problem, we can have single neuron in final layer.</p><p>We can also have multiple <strong>INPUT FEATURES </strong>as well which can help us to generate more features. We can also increase the size of hidden layer which will extract some features from existing data. Now these features can be further be used to extract some more new features. To do so, we can add more layers for creating new features. So, considering the below example we see that we have 2 hidden layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*xs6qoK9bvs4F4BRSqoCQbw.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>Link: <a href="https://playground.tensorflow.org/#activation=sigmoid&amp;batchSize=10&amp;dataset=gauss&amp;regDataset=reg-plane&amp;learningRate=0.03&amp;regularizationRate=0&amp;noise=0&amp;networkShape=4&amp;seed=0.04377&amp;showTestData=false&amp;discretize=false&amp;percTrainData=50&amp;x=true&amp;y=true&amp;xTimesY=false&amp;xSquared=false&amp;ySquared=false&amp;cosX=false&amp;sinX=false&amp;cosY=false&amp;sinY=false&amp;collectStats=false&amp;problem=classification&amp;initZero=false&amp;hideText=false">TensorFlow Playground </a>(You all can visit TensorFlow Playground link to visualize neural network and play with values)</p><p><strong><em>SOME BACKGROUND — TENSORFLOW PLAYGROUND</em></strong></p><p>Neural network works differently in identifying the decision boundaries. Initially weights and bias are randomly initialized. Referring to TensorFlow Playground X1 (Vertical position) and X2(Horizontal position) represent input features. If we just consider X1 and X2 we can derive at a naïve decision which will not fit our solution which we want.</p><p>Neural network considers the decisions such as vertical or horizontal decision boundaries along with diagonal decisions boundaries made by neurons in hidden layers, combines all of them and makes a final decision.</p><blockquote><strong>FORWARD &amp; BACWARD PROPAGATION — INTUITION.</strong></blockquote><p>In neural network weights of layers are constantly updated to improve the predictions. Let us understand that with a simple example.</p><p>Let us assume we have following 3 features X1, X2 and X3. These features are sent to the first hidden layer and connection between inputs and hidden layers are assigned some weights and bias. Based upon the weights and bias we would be getting some outputs. Previously in perceptron we denoted the output as Z but since we have more neurons now, we will denote as Z11 which denotes output from 1st neuron, 1st layer. After this we apply activation function which can be denoted as H11. Same things are done for 2nd neuron which would result into Z12 and H12. The outputs (H11 and H12) are then sent to next layer. Again, some random weights and bias are initialized, and same process is repeated and Z21 is calculated. Post that we apply the activation function to generate the final output. The output here is denoted as ‘O’. This complete process is called as <strong>FORWARD PROPAGATION.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*iLeoE5Tsj2I9DiuRZSl1pQ.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>The output ‘O’ which we obtained may or may not be correct. Let say actual value was 1 (Loan Approved) but our model predicted as 0.3 (Loan Not Approved). So, we see that predictions are incorrect. So, to deal with that we will calculate the error e.g. MSE (Mean Square Error) which calculates the square difference between actual and predicted values. When the predictions are large it implies that predictions are different from the actual value. This is the error for single observation. We calculate this error for all the observations and called it as <strong>COST FUNCTION / LOSS FUNCTION / ERROR FUNCTION.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*saE8EyInLRKBQybWt5ZvCw.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>Our task is to minimize this error function. This error is clearly dependent on output Y and output O. We cannot change the output Y as these are the actual target values, so we are left with changing the output O. The value of O is dependent upon various factors like input features, weights, biases, and activation function. Out of the 4 factors we cannot change the input feature as they are fixed also activation function, we need to define at the start of the training process. These are called as hyperparameters which we define before the start of training process. The only thing which we can change are the weights and bias during the training process which are known as parameters. So to reduce the error we need to update the weights and bias of the network and send back again for training with updated weights exactly what we saw in TensorFlow Playground. This process of updating the weights in neural network is called as <strong>BACKWARD PROPAGATION.</strong></p><p>One question which would be arising in our mind is that how we will update our weights and bias to improve the predictions of the model. To do that we introduce <strong>GRADIENT DESCENT</strong></p><blockquote><strong>GRADIENT DESCENT.</strong></blockquote><p>To discuss about how we update our weights let us understand the methodology. One such method could be updating the weights and bias manually and plot the cost function against the weights or bias values. For simplicity purpose in below figure we consider plot for only single weight and omit the rest of the weights and biases to understand it better. Also, there are 2 important things we must consider while deciding the error or cost function first, it should be continuous and second, it should be differentiable at each point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*h-E_4S5c4R4C4gx3zIBILw.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>Suppose now we initialize our neural network with weights and performed forward propagation and got error as highlighted in figure 1 below. Our aim is to reach the minimum point. Now suppose we randomly updated the weight values and it gave us following new error in figure 2. We see that error has been reduced. Suppose again we update the weights and we saw increase in the cost function which can been seen in figure 3. So, it is totally by random chance we will get the lowest error. What should be our right approach?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*kejCfTUpr6qX9tD3HJefYA.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>Considering below figure we need to follow 2 things to get the lowest error.</p><p>1) Direction of movement.</p><p>2) Magnitude of the movement.</p><p>In our case, we will be moving towards left side and by how much. So, in this place <strong>GRADIENT DESCENT</strong> comes into picture to help us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*fiKsSjuNzWU3o-4HzCBViA.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>The gradient descent equation is given as: <strong>w = w — alpha * dE/dw.</strong></p><p><strong>dE/dw</strong> -&gt; rate of change of error with respect to weights.</p><p>The sign of the partial derivative tells us in which direction we should move so that error is minimized.This is why we need continuous and differnetiable cost function because we calculate the partial derivative to update the weights and bias. The magnitude of the partial derivative tells us how much we should move in that particular direction.</p><p><strong>alpha</strong> -&gt; learning rate.</p><p>This is used to control the updation of the parameters in terms of magnitude. So, we should update the value of W by 0.1 times of dE/dW or 10 times of dE/dW that depends upon the value of alpha which we set. If we keep learning rate too high the error will fluctuate much and we might not reach up ending the minima. Also, if we set the alpha value to low the updates will be very slow and we would be needing more iterations to reach minimum value. So, deciding right value of alpha is very crucial while defining your model. Generally it is set to value between 0.001 to 0.01.</p><p><strong><em>STEPS TO PERFORM GRADIENT DESCENT.</em></strong></p><p>1) We will take current value of w and b.</p><p>2) Take a step in stephest downhill direction.</p><p>3) Repeat the previous step untill minima is reached.</p><p>At initial value of w we can observe the value of cost function as below and calculate the partial derivative at that point. We will see the slope turns out to be positive and the updated weight would be the prevoius weight minus some positive value as alpha and dE/dw are positive which means weight will be reduced and we will move in left direction (If slope is positive we reduce the value of weight). This is how gradient descent works in minimizing the cost functions by updating the parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*HAQhaGmEEPwQIq5vk0Vl2A.png" /><figcaption>Source: Analytics Vidhya</figcaption></figure><p>We can also stop updating the parameters (weights) if the number of iterations is achieved i.e. say nos. of epochs to be 100 which means even if minimum loss is not achieved we will stop the gradient descent algorithm after 100 epochs or errors have stopped updating anymore.</p><p><strong>CONCLUSION:</strong></p><p>Here is a quick recap what we have done so far. We had set of inputs. These inputs where send to hidden layer and we calculated the Z value which was sum of the inputs multiplied by the weights. After this operation we used activation function to calculate output H. We used sigmoid activation function. The results where then sent to next layer where we had some weights and bias and we then calculated output O.</p><p>Hope you liked it. If so please give a thumps up :)</p><p>Do connect with me on LinkedIn : <a href="https://www.linkedin.com/in/gaurav-rajpal/">https://www.linkedin.com/in/gaurav-rajpal/</a></p><p><strong><em>Stay tuned for further updates on Activation Function / Optimizers and demo projects on Deep Learning.</em></strong></p><p>Regards,</p><p>Gaurav Rajpal (gauravrajpal1994@gmail.com)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d111bb4649" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/introduction-to-neural-networks-1d111bb4649">Introduction To Neural Networks</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Underfitting vs. Overfitting (vs. Best Fitting) in Machine Learning]]></title>
            <link>https://medium.com/analytics-vidhya/underfitting-vs-overfitting-vs-best-fitting-in-machine-learning-1af6c6961d89?source=rss-a26b76928645------2</link>
            <guid isPermaLink="false">https://medium.com/p/1af6c6961d89</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[overfitting]]></category>
            <category><![CDATA[underfitting]]></category>
            <category><![CDATA[analytics-vidhya]]></category>
            <dc:creator><![CDATA[Gaurav Rajpal]]></dc:creator>
            <pubDate>Sun, 27 Sep 2020 09:34:25 GMT</pubDate>
            <atom:updated>2020-10-05T12:45:54.968Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Challenge of Underfitting and Overfitting in Machine Learning.</h3><p>Your ability to explain this in a non-technical and easy-to-understand manner might well decide your fit for the data science role!</p><p>Even when we’re working on a <a href="https://courses.analyticsvidhya.com/courses/applied-machine-learning-beginner-to-professional?utm_source=blog&amp;utm_medium=underfitting-overfitting-best-fitting-machine-learning">machine learning</a> project, we often face situations where we are encountering unexpected performance or error rate differences between the training set and the test set (as shown below). How can a model perform so well over the training set and just as poorly on the test set?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/0*XsL0yDoAQ2GD1_VL.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>Here’s my personal experience — ask any seasoned data scientist about this, they typically start talking about some array of fancy terms like Overfitting, Underfitting, Bias, and Variance. But little does anyone talk about the intuition behind these machine learning concepts. Let’s rectify that, shall we?</p><h3>Let’s Take an Example to Understand Underfitting vs. Overfitting</h3><p>I want to explain these concepts using a real-world example. A lot of folks talk about the theoretical angle but I feel that’s not enough — we need to visualize how underfitting and overfitting actually work.</p><p>So, let’s go back to our college days for this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eQyMAK8y2MQAyonO.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>Consider a math class consisting of 3 students and a professor.</p><p>Now, in any classroom, we can broadly divide the students into 3 categories. We’ll talk about them one-by-one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QqUwiQJAFnxWIBSV.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>Let’s say that student A resembles a student who does not like math. She is not interested in what is being taught in the class and therefore does not pay much attention to the professor and the content he is teaching.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CEji5it6BMvTwm00.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>Let’s consider student B. He is the most competitive student who focuses on memorizing each and every question being taught in class instead of focusing on the key concepts. Basically, he isn’t interested in learning the problem-solving approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nqDTUrvmVD841O90.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>Finally, we have the ideal student C. She is purely interested in learning the key concepts and the problem-solving approach in the math class rather than just memorizing the solutions presented.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*huaHzO44uYQz1AXx.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>The obstacle comes in the semester tests that the school lays down. This is where new questions (unseen data) comes up. The students haven’t seen these questions before and certainly haven’t solved them in the classroom. Sounds familiar?</p><p>So, let’s discuss what happens when the teacher takes a classroom test at the end of the day:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*71fQvNVYiYetw1Tx.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><ul><li>Student A, who was distracted in his own world, simply guessed the answers and got approximately 50% marks in the test</li><li>On the other hand, the student who memorized each and every question taught in the classroom was able to answer almost every question by memory and therefore obtained 98% marks in the class test</li><li>For student C, she actually solved all the questions using the problem-solving approach she learned in the classroom and scored 92%</li></ul><p>We can clearly infer that the student who simply memorizes everything is scoring better without much difficulty.</p><p>Now here’s the twist. Let’s also look at what happens during the monthly test, when students have to face new unknown questions which are not taught in the class by the teacher.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aKjl8Dm6-ybUoMzO.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><ul><li>In the case of student A, things did not change much and he still randomly answers questions correctly ~50% of the time.</li><li>In the case of Student B, his score dropped significantly. Can you guess why? This is because he always memorized the problems that were taught in the class but this monthly test contained questions which he has never seen before. Therefore, his performance went down significantly</li><li>In the case of Student C, the score remained more or less the same. This is because she focused on learning the problem-solving approach and therefore was able to apply the concepts she learned to solve the unknown questions</li></ul><h3>How Does this Relate to Underfitting and Overfitting in Machine Learning?</h3><p>You might be wondering how this example relates to the problem which we encountered during the train and test scores of the decision tree classifier? Good question!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ckm9P7GpG4eRJxG_.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>So, let’s work on connecting this example with the results of the decision tree classifier that I showed you earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/0*PmoMlXUPXjCFcKTh.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><p>First, the classwork resemble the training data and the prediction over the training data itself respectively. On the other hand, the semester test represents the test set from our data which we keep aside before we train our model (or unseen data in a real-world machine learning project).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/0*j3iLopzNc3rjTnS2.png" /></figure><p><strong>NOTE</strong>: <strong>This situation where any given model is performing too well on the training data but the performance drops significantly over the test set is called an overfitting model.</strong></p><p>The graph below summarizes this concept:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/0*qobsUD7leXLqx2Hz.png" /><figcaption>Source : Analytics Vidhya</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/0*ZNLlHO7UYFmfk62G.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/0*EX3Fvy9bf7jBq4jz.png" /><figcaption>Source: Internet</figcaption></figure><h3>End Notes</h3><p>I hope this short intuition has cleared up any doubts you might have had with underfitting, overfitting, and best-fitting models and how they work or behave under the hood.</p><p>Feel free to shoot me any questions or thoughts. Don’t forget to hit like button.</p><p>LinkedIn: <a href="http://www.linkedin.com/in/gaurav-rajpal">https://www.linkedin.com/in/gaurav-rajpal/</a></p><h3>References</h3><p>Analytics Vidhya — Machine Learning Course ( Beginner — Advance)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1af6c6961d89" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/underfitting-vs-overfitting-vs-best-fitting-in-machine-learning-1af6c6961d89">Underfitting vs. Overfitting (vs. Best Fitting) in Machine Learning</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>