<?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[#ByCodeGarage - Medium]]></title>
        <description><![CDATA[Welcome to #ByCodeGarage, where you can share and find concepts, ideas on Emerging Technologies. Share your story with us! - Medium]]></description>
        <link>https://medium.com/bycodegarage?source=rss----4826d9cea60e---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>#ByCodeGarage - Medium</title>
            <link>https://medium.com/bycodegarage?source=rss----4826d9cea60e---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 05:22:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/bycodegarage" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building blocks of Angular]]></title>
            <link>https://medium.com/bycodegarage/building-blocks-of-angular-eafbb289b6d6?source=rss----4826d9cea60e---4</link>
            <guid isPermaLink="false">https://medium.com/p/eafbb289b6d6</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Akhil Reddy Mallidi]]></dc:creator>
            <pubDate>Sun, 24 May 2020 13:09:48 GMT</pubDate>
            <atom:updated>2020-05-24T13:09:48.378Z</atom:updated>
            <content:encoded><![CDATA[<h4>This story deals or goes through various building blocks that will be helpful while building an Angular application. This story is the continuation of Angular series. If your completely new to Angular and thinking of getting start with it, <a href="https://medium.com/bycodegarage/creating-an-angular-app-377f961b51c6">check out my previous story </a>in this series where i have discussed about setting up Angular environment in your local system and even by the end of that story, you will be running your First Angular app locally.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*GzAdw1m8xTMQapMkyOXh3A.jpeg" /></figure><p>Let’s get started. The various building blocks in Angular are as follows:</p><ol><li>Components</li><li>Modules</li><li>Directives</li><li>Decorators</li><li>Pipes</li><li>Data Binding</li><li>Templates</li><li>Metadata</li><li>Services</li><li>Dependency Injection</li></ol><h4>Components</h4><p>A component refers to a Javascript class, which in turn rendered as section in a View. In simpler terms, a component encapsulates the Data, HTML Template and Logic in a view.Generally every angular app, will have atleast one component. That is app.component.ts. A component is a Javascript class which is decorated with @Component decorator. The component decorator takes parameters like selector for defining the component custom tag, by which we can render that component where ever we want in our application and also other parameters like template, templateUrl, styles and stylesUrl.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b764e1951ceb1243841770a494f92c60/href">https://medium.com/media/b764e1951ceb1243841770a494f92c60/href</a></iframe><h4>Modules</h4><p>Angular applications maintain modularity. In simpler terms, Module in an Angular refers to a file which group similar components, directives, pipes, services which does or perform a certain task. Every angular application will have atleast one root module and its is generally app.module.ts. Like component, module is also an javascript class that is decorated by @NgModule decorator. NgModule decorator takes parameters like declarations, imports, providers etc.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39176f1e226fb2657e2ba9c6701298d3/href">https://medium.com/media/39176f1e226fb2657e2ba9c6701298d3/href</a></iframe><h4>Directives</h4><p>Directives in angular, helps us to add dynamic content the DOM elements. Angular has two types of directives.</p><ol><li><strong>Structural Directives</strong></li></ol><p>Structural directives are the one, that modifies the structure of the DOM elements like presence/removing an element from the DOM. These directives are added along with * (asterisk).</p><p>*ngIf, *ngFor, ngSwitch &amp; *ngSwitchCase are examples of structural directives.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cb3cbd85cbc8ae06b017c8c3b680c03/href">https://medium.com/media/3cb3cbd85cbc8ae06b017c8c3b680c03/href</a></iframe><p>2. <strong>Attribute Directives</strong></p><p>Attribute directives are the one’s that alters the appearance or behavior of an existing element in a DOM.</p><p>ngClass, ngStyle, ngModel, formGroup, and formControlName are some of the examples of attribute directives</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/912396c44c47d0182d504460f0db57dd/href">https://medium.com/media/912396c44c47d0182d504460f0db57dd/href</a></iframe><h4>Decorators</h4><p>Decorators in angular are annotated with @, which helps to define metadata for any javascript classes like components, directives, services and modules etc.</p><p>Some of the decorators available are:</p><p>@NgModule</p><p>@Directive</p><p>@Component</p><p>@Injectable</p><p>@Pipe</p><p>@Input</p><p>@Output</p><p>@HostBinding</p><p>@ViewChild</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b61e48d98946629ecb70d1273aecca0/href">https://medium.com/media/9b61e48d98946629ecb70d1273aecca0/href</a></iframe><p>In angular, we can have flexibility of developing custom directives.</p><h4>Pipes</h4><p>Angular provides us a lot of built in pipes, which helps us to transform data in the template. Usually pipes are functions that accepts input and transforms those text into specified format and returns as output.</p><p>Some of the pipes available are:</p><p>Currency Pipe</p><p>Date Pipe</p><p>Uppercase Pipe</p><p>Lowercase Pipe</p><p>Decimal Pipe</p><p>JSON Pipe</p><pre>// Currency Pipe </pre><pre>{{ priceToPay | currency:&#39;INR&#39; }}</pre><p>In angular, we can have flexibility of developing custom pipes.</p><h4>Data Binding</h4><ol><li>Interpolation</li><li>Property Binding</li><li>Event Binding</li><li>Two way Binding</li></ol><p>Interpolation binds any javascript variable data to the template</p><pre>&lt;p&gt; {{ name }} &lt;/p&gt;</pre><p>Property binding allows binding of any javascript variable value to any property or attribute of an html element.</p><pre> &lt;app-message [message] = &quot;messageToDisplay&quot;&gt;&lt;/app-message&gt;</pre><p>Event binding binds any native element to javascript function and triggers the function when the event occurs.</p><pre>&lt;p (click) = &quot;onClick()&quot;&gt;This is paragraph &lt;/p&gt;</pre><p>Binding javascript variable to the input field, and also to capture the input field data is called Two way binding</p><pre>&lt;input [(ngModel)]=&quot;user.name&quot;&gt;</pre><h4>Templates</h4><p>The view of the component is defined through templates. Templates are basically the HTML we use to show on our page.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d8fa1f31569ab8abd0ab2876e110551/href">https://medium.com/media/1d8fa1f31569ab8abd0ab2876e110551/href</a></iframe><h4>Metadata</h4><p>Metadata in angular tells a javascript class, how it should be processed on screen. Usually we will pass meta data in the decorator’s.</p><pre>@Component({</pre><pre>selector: &#39;app-root&#39;,</pre><pre>templateUrl: &#39;./app.component.html&#39;,</pre><pre>styleUrls: [&#39;./app.component.css&#39;]</pre><pre>})</pre><h4>Services</h4><p>A service is a class containing any function, feature with a defined, and specific purposes like performing side effects like HTTP requests. This makes our angular app more modular, means instead of writing same code in different components we will inject the service and calls the method in the service that triggers HTTP requests.</p><h4>Dependency Injection</h4><p>Dependency Injection allows us to inject any dependency or service and can provide its instance through out entire web application or any particular module or component.</p><pre>constructor(private authService : AuthService) { }</pre><p>Tada..!! Now you have gained good foundation on basics required to kick start developing applications in Angular.</p><p><strong>𝚃𝚑𝚊𝚗𝚔𝚜 𝚏𝚘𝚛 𝚛𝚎𝚊𝚍𝚒𝚗𝚐..!!</strong></p><p>𝙷𝚘𝚙𝚎 𝚢𝚘𝚞 𝚕𝚒𝚔𝚎𝚍 𝚖𝚢 𝚊𝚛𝚝𝚒𝚌𝚕𝚎. 𝙳𝚘 𝚜𝚑𝚊𝚛𝚎 𝚝𝚑𝚎 𝚊𝚛𝚝𝚒𝚌𝚕𝚎 𝚒𝚏 𝚢𝚘𝚞 𝚏𝚒𝚗𝚍 𝚒𝚝 𝚠𝚒𝚕𝚕 𝚋𝚎 𝚞𝚜𝚎𝚏𝚞𝚕 𝚝𝚘 𝚢𝚘𝚞𝚛 𝚙𝚎𝚎𝚛𝚜.</p><p>𝙻𝚎𝚝 𝚖𝚎 𝚔𝚗𝚘𝚠 𝚒𝚏 𝚢𝚘𝚞 𝚑𝚊𝚟𝚎 𝚊𝚗𝚢𝚝𝚑𝚒𝚗𝚐 𝚝𝚘 𝚊𝚜𝚔 𝚒𝚗 𝚌𝚘𝚖𝚖𝚎𝚗𝚝𝚜 𝚜𝚎c𝚝𝚒𝚘𝚗 :)</p><p><a href="https://itzzmeakhi.github.io/me/"><strong><em>𝚁𝚎𝚊𝚌𝚑 𝚖𝚎 𝚘𝚞𝚝 𝚑𝚎𝚛e</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eafbb289b6d6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bycodegarage/building-blocks-of-angular-eafbb289b6d6">Building blocks of Angular</a> was originally published in <a href="https://medium.com/bycodegarage">#ByCodeGarage</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating an Angular App]]></title>
            <link>https://medium.com/bycodegarage/creating-an-angular-app-377f961b51c6?source=rss----4826d9cea60e---4</link>
            <guid isPermaLink="false">https://medium.com/p/377f961b51c6</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Akhil Reddy Mallidi]]></dc:creator>
            <pubDate>Mon, 23 Mar 2020 10:36:56 GMT</pubDate>
            <atom:updated>2020-03-23T10:37:06.195Z</atom:updated>
            <content:encoded><![CDATA[<h4>This story is strictly for complete beginners who are getting started with Angular Ecosystem and also for dev’s who facing issues while setting Angular development environment locally. Throughout this story, I will go through the steps involved in setting up Angular development environment locally.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f4PHh2EAcohEMHaw0vaprQ.jpeg" /></figure><p>To get start with Angular setup, We need to install the following in our system.</p><ol><li>Node</li><li>NPM</li><li>Angular CLI</li><li>Any IDE(Integrated Development Environment) you like. I will prefer Visual Studio Code.</li></ol><p><strong><em>Setting up Node in our local system.</em></strong></p><p>Node is a Javascript run time environment which Angular uses to build the application that was developed using Angular and also to run that application.</p><p>To install Node, head over to the official <a href="https://nodejs.org/en/"><strong><em>Nodejs website by clicking here.</em></strong></a></p><p><a href="https://nodejs.org/en/">Node.js - Run JavaScript Everywhere</a></p><p>You can download the stable or long time support version or the latest version.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0WVB-VdCFyYBQ-L7gtCMfA.jpeg" /></figure><p>Download the installer an try running the installer and continue the installation steps. You can configure the installation directory or can install using the default configurations by clicking on next.</p><p>After installation we can verify for the successful installation by checking the node version. We can check the node version installed locally, by running this command in the Command Line Interface(CLI).</p><pre>// To check for the node version installed locally</pre><pre>node --version</pre><p>NPM is a Node Package Manager, that is used for managing packages or dependencies that we will be using in our node based projects. NPM will also be installed, along with node. Try checking the NPM version installed locally, by running this command in the Command Line Interface(CLI).</p><pre>// To check for the npm version installed locally</pre><pre>npm --version</pre><p><strong><em>Installing Angular CLI</em></strong></p><p>For building an Angular application, we need to install a lot of dependencies. For making all this hectic work done for us and also to manage the versions of dependencies that are installed in our project, we have Angular CLI. Angular team supports Angular CLI.</p><p>Using Angular CLI we can create a new Angular project, can create an Angular component/directive/service/model/class etc. We will go through deep about what is a component? or what is a directive? etc in coming stories.</p><p>To install Angular CLI in our system, try running this command in the Command Line Interface(CLI).</p><pre>// To install Angular CLI globally</pre><pre>npm install @angular/cli@latest -g</pre><p><em>The </em><em>-g flag indicates that the installation is done globally through out our system.</em></p><p>You can check the Angular CLI version, by running the following command in the Command Line Interface(CLI).</p><pre>// To check for angular cli version</pre><pre>ng --version</pre><p><strong>IDE</strong></p><p>IDE is your choice, and I will prefer <a href="https://code.visualstudio.com/"><strong><em>Visual Studio Code</em></strong></a>. It is free version and there are lot of available plugins which helps us in development and also in debugging. You can install and use your IDE, if you have any preference.</p><p><a href="https://code.visualstudio.com/">Visual Studio Code - Build what comes next</a></p><p>Tada…!! The installation process is done. Now we will start creating our first basic Angular Application.</p><pre>// To create an Angular Application</pre><pre>ng new ApplicationName</pre><p>Here ApplicationName indicates the name that you want your application to have. For example I have created an application with name CreateAngularApp by executing the above ng command as follows</p><pre>ng new CreateAngularApp</pre><p>It will take few minutes to install the dependencies, that are required to build a basic Angular app. After successful creation of an new Angular app, you can see a folder with Application Name you have given while creating an Angular app in your Current Working Directory.</p><p>Angular CLI also installed an HTTP Server in our project directory for us to start spinning server to view/access our application locally, <em>via localhost. </em>Angular also installs change detection, so that we can view our changes that are made to our application in live. Don’t worry, you don’t need to configure them. Angular configures all of them for us with default settings.</p><p>To spin a local server, run the following commands in the Command Line Interface(CLI).</p><pre>// To change our working directory to project directory</pre><pre>cd CreateAngularApp</pre><pre>// To spin a server locally</pre><pre>ng serve</pre><p>The Angular CLI, then builds all our files in the application into bundles(minimized versions of all our files in the app) and then starts spinning the server locally.</p><p>By default, the application is being served at <a href="http://localhost:4200/">http://localhost:4200/.</a> Angular uses port number 4200 by default. If that port is occupied by any another application, you can configure port number by using -p or -port flag.</p><pre>ng server -port=4300</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aMr1GKyl1mF1R2L-EgLt0A.jpeg" /><figcaption><strong>Our app being served in localhost</strong></figcaption></figure><p>Let’s get more detailed knowledge about all the files that were created by Angular CLI while creating our application. Open our application folder in any IDE you like. The project directory will look something similar to this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*ftweGfv_Ni-Guk4Qb5kEUg.jpeg" /><figcaption><strong>Project directory looks some like this</strong></figcaption></figure><p>Let’s know about more about all these files and other directories which are present in our project directory.</p><ol><li><strong>e2e : </strong>This folder will contain all files which are used to perform End to End testing to our application.</li><li><strong>node_modules :</strong> These are installed dependencies in our project.</li><li><strong>src :</strong> This is the folder where all our application source code lies.</li><li><strong>.editorconfig :</strong> This is a configuration file related to our IDE.</li><li><strong>.gitignore :</strong> This is a configuration file, which ignores the files/folders that are listed in it while pushing our project to GIT (Version Management Tool).</li><li><strong>angular.json :</strong> This is a configuration file related to Angular CLI.</li><li><strong>browserlist :</strong> A configuration file related to browser, where we can define on which browsers which are compatible with our app.</li><li><strong>karma.config.js :</strong> A configuration file related to Unit Testing our application.</li><li><strong>package.json/package-lock.json</strong> : Configuration files related to NPM. These are used to record and lock the dependencies version’s.</li><li><strong>tslint.json</strong> : Configuration file related to typescript linter.</li><li><strong>tsconfig.app.json/tsconfig.json</strong> : Configuration file related to Typescript.</li></ol><h4><strong><em>Entry point of our app:</em></strong></h4><p>The Angular CLI from its configuration file angular.json sees for the entry point for our application. By default, if an app is created using Angular CLI it is main.ts file. Open angular.json file, you can see that main.ts file is defined with the main attribute in the project configurations.The main.ts is the entry point of our app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*6uO9pBqmvtYe4XwirqND8A.jpeg" /><figcaption><strong>angular.json file</strong></figcaption></figure><p>The main.ts file bootstraps the AppModule.ts file. In simple terms it will trigger AppModule.ts file. We will go through the modules in coming stories. Right now, think of Module as a collection of components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*8U4aBrsjkp-Ay_ULR-WiSQ.jpeg" /><figcaption><strong>main.ts file</strong></figcaption></figure><p>From there, AppModule.ts bootstraps or triggers any component that are declared under that module. That component will be rendered in the browser. Remember component is a combination of *.css, *.html and .*.ts files. In our case, AppComponent will be triggered from the AppModule.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*jQQoctRB1p--XvqXEhJyew.jpeg" /><figcaption><strong>AppModule.ts file</strong></figcaption></figure><h4>Editing our first app:</h4><p>In general, angular app has atleast one Module and every Module has atleast one Component. In our app which was generated using Angular CLI, the angular cli generates one module which was AppModule and one component which was AppComponent.</p><p>In every component, for example AppComponent</p><p>app.component.ts : holds all typescript logic</p><p>app.component.html : holds all template part (HTML) of our component.</p><p>app.component.css : holds all CSS styles, for the template</p><p>Now head over to app.component.hml and remove all the code that was generated by Angular CLI. Now add any basic HTML code and save that file. In my case, I have added the following code to the app.component.html.</p><pre>&lt;p&gt;<br>    This is a Demo project.<br>&lt;/p&gt;</pre><p>What are you waiting for, head over to the browser to view the changes. Angular runs change detection in background, so the changes are automatically detected and updated in the DOM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*PCa7CNkE-XN1qcCOgieFww.jpeg" /></figure><p>Tada..!! Now you have gained good foundation on setting up Angular development environment and also basics required to kick start developing applications in Angular.</p><p><strong>𝚃𝚑𝚊𝚗𝚔𝚜 𝚏𝚘𝚛 𝚛𝚎𝚊𝚍𝚒𝚗𝚐..!!</strong></p><p>𝙷𝚘𝚙𝚎 𝚢𝚘𝚞 𝚕𝚒𝚔𝚎𝚍 𝚖𝚢 𝚊𝚛𝚝𝚒𝚌𝚕𝚎. 𝙳𝚘 𝚜𝚑𝚊𝚛𝚎 𝚝𝚑𝚎 𝚊𝚛𝚝𝚒𝚌𝚕𝚎 𝚒𝚏 𝚢𝚘𝚞 𝚏𝚒𝚗𝚍 𝚒𝚝 𝚠𝚒𝚕𝚕 𝚋𝚎 𝚞𝚜𝚎𝚏𝚞𝚕 𝚝𝚘 𝚢𝚘𝚞𝚛 𝚙𝚎𝚎𝚛𝚜.</p><p>𝙻𝚎𝚝 𝚖𝚎 𝚔𝚗𝚘𝚠 𝚒𝚏 𝚢𝚘𝚞 𝚑𝚊𝚟𝚎 𝚊𝚗𝚢𝚝𝚑𝚒𝚗𝚐 𝚝𝚘 𝚊𝚜𝚔 𝚒𝚗 𝚌𝚘𝚖𝚖𝚎𝚗𝚝𝚜 𝚜𝚎c𝚝𝚒𝚘𝚗 :)</p><p><a href="https://itzzmeakhi.github.io/me/"><strong><em>𝚁𝚎𝚊𝚌𝚑 𝚖𝚎 𝚘𝚞𝚝 𝚑𝚎𝚛e</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=377f961b51c6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bycodegarage/creating-an-angular-app-377f961b51c6">Creating an Angular App</a> was originally published in <a href="https://medium.com/bycodegarage">#ByCodeGarage</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Linear Regression in a Comprehensive way]]></title>
            <link>https://medium.com/bycodegarage/simple-linear-regression-in-a-comprehensive-way-e290a1358a6d?source=rss----4826d9cea60e---4</link>
            <guid isPermaLink="false">https://medium.com/p/e290a1358a6d</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Akhil Reddy Mallidi]]></dc:creator>
            <pubDate>Thu, 05 Sep 2019 03:10:06 GMT</pubDate>
            <atom:updated>2019-09-06T03:56:02.410Z</atom:updated>
            <content:encoded><![CDATA[<h4>Regression is a form of predictive modelling technique, which investigate’s the relationship between independent and dependent vectors. Regression is of many types and Linear Regression is one among them. Linear Regression predicts the dependent vector by assuming the relationship between the independent and dependent vector is a straight line</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*O6mrRdZc0a1hE2NwcI2UzA.png" /></figure><h4>What is Simple Linear Regression ?</h4><blockquote>It’s the easiest approach among the Regression models. Simple Linear Regression is applied only when our data has one independent variable and it predicts the dependent vector, by estimating the relation among the dependent and independent vectors as a straight line. It expresses the relation among the dependent and independent vector’s as a straight and is in the form as below.</blockquote><pre>y = mx + c</pre><pre>where<br>y is the dependent vector<br>x is the independent vector<br>c is the constant and also called as bias, which is added to the line<br>m is slope and it is an offset that equals both vectors</pre><p>Mathematically, c is the y-intercept that determines the value of y when x is 0 and m is the slope which determines the angle of line.</p><h4>How it works?</h4><p>The Simple Linear Regression model assumes and plots a Regression line, in such a way that the Regression line should be as close as to all data points of the dataset. To get more clear idea about how it works, let’s go through an example. We have an salary dataset comprised of Years of Experience and Salary. The dataset is as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/222/1*qmmWsExTuOj6X3gq4Dk0tQ.png" /><figcaption><strong>Overview of dataset</strong></figcaption></figure><p>Here dependent variable is salary and independent variable is YearsExperience. If there is an increase in dependent variable when independent variable increases, then there is a positive correlation among them. If decreases, then there is a negative correlation among them.</p><p>Now let’s plot a scatter plot among YearsExperience and Salary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*Vrzl3bhDCVyG94C94xNxKw.png" /><figcaption><strong>Scatter plot Experience VS Salary</strong></figcaption></figure><p>The best fit line for the data is the one which produces least error or least square approximation error among all regression line’s that can be drawn. This method of finding best fit line is called Least Square Approximation Method.</p><p>Now let’s get started by drawing an regression line among the data points in the scatter plot using mean of independent and dependent vectors. Draw a line across the point such that the point will be the mean of two vectors.</p><pre>Xm ( Mean) = Sum of all experience values / Total number of experience values<br>Ym (Mean) = Sum of all salary values / Total number of salary values</pre><p>Now plot a line which will be our assumed regression line over the data ponts in the scatter plot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*qOO5QoNO0Xrz4F6ACwMHqw.png" /><figcaption><strong>Regression line plotted using mean</strong></figcaption></figure><p>From the above plot, we can observe that the regression line is some what far from some data points. This whole process is an iterable one and will be continued until the best fit line which is having the least square approximation distance is obtained.</p><p>The values corresponding to the original value on the regression line are called predicted values. The Least Approximation distance can be calculated as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*fLmzCD0gD5K9ejYIQiGWIw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*6cyNL35HYLH8kxWw2TodtQ.jpeg" /><figcaption><strong>Distance Approximation among original value and predicted value</strong></figcaption></figure><p>To calculate the regression line, for which the approximation distance is minimum when compared to the regression line now.</p><p>The slope or multiplier of new regression line can be calculated as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*w4sRNsS0-FNxbUlqdR5Qtg.png" /></figure><p>where Xi, Yi are the values of independent vector and dependent vectors. They are subtracted from their corresponding mean’s and the slope of new regression line is calculated.</p><p>Let’s calculate the slope for new regression line. You can view the whole calculation in the following table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*-YMdHh5MV6SzTtXvm0aCFQ.png" /></figure><p>Hence the summation of d*e and e*e are 1463496.36666667 and 3.366111111. The slope of the new regression cab be calculated from the above value’s and it is 0.00016808.</p><p>I have performed all the operation using python code. Have a look at it.</p><pre>Xm = np.mean(X_train)<br>Ym = np.mean(y_train)<br>sum1 = 0<br>sum2 = 0<br>print(&#39;Experience Salary     d=Xi-Xm               e=Yi-Ym             d*e                  e*e&#39;)<br>print(&#39;------------------------------------------------------------------------------------------------&#39;)<br>for pos in range(0, len(X_train)):<br>    d = (X_train[pos] - Xm)<br>    e = (y_train[pos] - Ym)<br>    sum1 = sum1 + d*e<br>    sum2 = sum2 = d*d<br>    print(f&#39;{str(X_train[pos]):{10}} {str(y_train[pos]):{10}} {str(X_train[pos]-Xm):{20}} {str(y_train[pos]-Ym):20} {str(d*e):{20}} {str(d*d):{20}}&#39;)</pre><p>From the slope, we can calculate the y-intercept or bias by substituting x and y as zero in y-mx+c equation.</p><p>The obtained line equation is the new regression line and this process is continued for all regression line that cab be possibly drawn in our scatter plot. The regression line with minimum least square approximaton error is called best fit line.</p><p>Don’t worry, python’s scikit learn library does all these hectic work for us.</p><h4>R-square Regression Analysis</h4><blockquote>To check how efficient is our model fits to the data, we can use the R-square Regression analysis method. This method is also called Coefficient of determination. Higher the R-square value, higher the efficiency of our model. But not all R-square value models are bad, it is based on the problem statement.</blockquote><blockquote>We can find the R-square value of the model in the following way.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*RS08NFUUFhMuDH_SXfDq5A.png" /></figure><p>where Yp is the predicted dependent variable, y is the actual or original dependent variable and Ym is the mean of the dependent variable. Like in the Least square Approximation method we can calculate R-square value.</p><p>Let’s implement Simple Linear Regression on Salaries data. Firstly, import all the necessary libraries and load the dataset.</p><pre># Importing the libraries</pre><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt</pre><pre># Loading the dataset</pre><pre>df = pd.read_csv(&#39;Salary_Data.csv&#39;)</pre><p>Now go through the data or perform some EDA (Exploratory Data Analysis), to understand and get familiar with the dataset.</p><pre># Viewing few rows of data</pre><pre>print(&#39;----- Few rows of data -----&#39;)<br>print(df.sample(10))</pre><pre>print(&#39;\n\n&#39;)<br>print(&#39;----- Features in the dataset ----&#39;)<br>print(df.columns)</pre><pre>print(&#39;\n\n&#39;)<br>print(&#39;---- Shape of the dataset -----&#39;)<br>print(df.shape)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*doB1OE_9nZRUau6aQSayCA.png" /><figcaption><strong>Some insights about the datset</strong></figcaption></figure><p>There are about 30 observations of data with two columns namely YearsExperience and Salary in our dataset. Our problem statement is to predict the salary based upon the experience(in years) he/she has. So YearsExperience is the independent variable and Salary becomes the dependent variable as per our problem statement.</p><p>Let’s have a look over our dataset for any missing values in the dataset.</p><pre># Check for null values</pre><pre>df.isnull().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*kpQeZx152jA-gcJqC8hMVA.png" /><figcaption><strong>Insights about Missing values in the dataset</strong></figcaption></figure><p>Hurrah..!! No missing values are present in the dataset. So no need of any data preprocessing, let’s jump directly into splitting our dataset into independent and dependent vectors.</p><pre># Converting dataset to dependent and independant vectors</pre><pre># YearsExperience<br>X = df.iloc[:, :-1].values</pre><pre># Salary<br>y = df.iloc[:, 1].values</pre><p>Now split the data into training and test data using scikit learn’s train_test_split method. I have spliced data in a way that 80 percent is training set and 20 percent is test set.</p><pre># Splitting the dataset into testing and training set&#39;s</pre><pre>from sklearn.model_selection import train_test_split</pre><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)</pre><p>Some insights about the dimensions of training and test data after splitting them.</p><pre># Dimensions of datset after splitting into testing and training set&#39;s</pre><pre>print(X_train.shape)<br>print(X_test.shape)<br>print(y_train.shape)<br>print(y_test.shape)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*UUDnx3OZctgk-0EfdcF5aw.png" /><figcaption><strong>Dimension of the resultant datsets</strong></figcaption></figure><p>Now the test and train dataset’s are ready. Let’s start importing the scikit learn’s LinearRegression model and instantiate it.</p><pre># Fitting Simple Linear Regression model to the training data</pre><pre>from sklearn.linear_model import LinearRegression</pre><pre># Instantiating LinearRegression Model</pre><pre>linear_regression = LinearRegression()</pre><pre># Fitting to the training data</pre><pre>linear_regression.fit(X_train, y_train)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*eUj9_uFh31cfaQe-a4xdbA.png" /><figcaption><strong>Output showing our Linear Regression model is trained</strong></figcaption></figure><p>The LinearRegression Model that was instantiated was fitted to our training data. Means a Regression line (a best fit line) with minimum least square approximation distance was identified. So from that regression line, our model starts predicting the output.</p><p>So start passing the test data to the model, to see the predictions of salary that our model predicts.</p><pre># Predicting dependent variable using independant variable</pre><pre>predictions = linear_regression.predict(X_test)</pre><p>Our Model has predicted the salaries of persons with respect to experience. Let’s view the predicted values and the original values together.</p><pre># Lets view predicted and original salaries</pre><pre>print(&#39;Predicted             -    Original&#39;)<br>for pos in range(0, len(predictions)):<br>    print(f&#39;{predictions[pos]:&lt;{25}}  {y_test[pos]:&lt;{15}}&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*AjWsCHdjDelvCoSEDhhXWg.png" /><figcaption><strong>Predicted and original values</strong></figcaption></figure><p>In some cases, the predicted values are very close to the original values and in some cases the predicted values are some what far but no too much from the original values. This is because our Regression Model learns the correlation among the variables by expressing as a straight line. So not all data points passed through the regression lines, due to outliers and some factors. So these causes these differences between and original target values. So that’s the reason that Linear Regression is not 100 percent accurate.</p><p>Let’s visualize the relationship between the independent variables with both predicted and original values along with the Regression line to get clear idea.</p><p>Now let’s plot a scatter plot between Experience and Salary of training dataset and along with Regression line.</p><pre># Training data VS Regression line<br># Regression line is drawn using predicted values for training set</pre><pre>plt.scatter(X_train, y_train, color=&#39;blue&#39;)<br>plt.plot(X_train, linear_regression.predict(X_train), color=&#39;red&#39;)<br>plt.title(&#39;Years VS Salary&#39;)<br>plt.xlabel(&#39;Years of Experience&#39;)<br>plt.ylabel(&#39;Salary&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*GaRLYLAzm52k_vlpcOOZvw.png" /><figcaption><strong>Original and Predicted values of training set</strong></figcaption></figure><p>Since it’s the best fit line, mostly every data point is very close to the Regression line. Now let’s plot a scatter plot between Experience and Salary of test dataset and along with Regression line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*tXqk7xfuEjUZTDdefxX1og.png" /><figcaption><strong>Original vs predicted values of test data</strong></figcaption></figure><p>Even the Regression line is very close to mostly every point in the test dataset.</p><p>Mean Square error and R-square regression can be performed in the following way.</p><pre>#import libraries</pre><pre>from sklearn.metrics import mean_squared_error,r2_score</pre><pre># model evaluation for training set</pre><pre>y_train_predict = linear_regression.predict(X_train)<br>rmse = (np.sqrt(mean_squared_error(y_train, y_train_predict)))<br>r2 = r2_score(y_train, y_train_predict)</pre><pre>print(&quot;The model performance for training set&quot;)<br>print(&quot;--------------------------------------&quot;)<br>print(&#39;RMSE is {}&#39;.format(rmse))<br>print(&#39;R2 score is {}&#39;.format(r2))<br>print(&quot;\n&quot;)</pre><pre># model evaluation for testing set</pre><pre>y_test_predict = linear_regression.predict(X_test)<br>rmse = (np.sqrt(mean_squared_error(y_test, y_test_predict)))<br>r2 = r2_score(y_test, y_test_predict)</pre><pre>print(&quot;The model performance for testing set&quot;)<br>print(&quot;--------------------------------------&quot;)<br>print(&#39;RMSE is {}&#39;.format(rmse))<br>print(&#39;R2 score is {}&#39;.format(r2))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*ILCK2nWQmwVFk4ilfdegSA.png" /><figcaption><strong>mean squared error and r2 error for train and test data</strong></figcaption></figure><p><strong>The complete Jupyter notebook cab be found below</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db402c56f5a9960e8a03df2d1afa8c5b/href">https://medium.com/media/db402c56f5a9960e8a03df2d1afa8c5b/href</a></iframe><p><a href="https://github.com/itzzmeakhi/Medium/tree/master/SimpleRegression"><strong><em>You can find the GitHub repository here</em></strong></a></p><p><strong>𝚃𝚑𝚊𝚗𝚔𝚜 𝚏𝚘𝚛 𝚛𝚎𝚊𝚍𝚒𝚗𝚐..!!</strong></p><p>𝙷𝚘𝚙𝚎 𝚢𝚘𝚞 𝚕𝚒𝚔𝚎𝚍 𝚖𝚢 𝚊𝚛𝚝𝚒𝚌𝚕𝚎. 𝙳𝚘 𝚜𝚑𝚊𝚛𝚎 𝚝𝚑𝚎 𝚊𝚛𝚝𝚒𝚌𝚕𝚎 𝚒𝚏 𝚢𝚘𝚞 𝚏𝚒𝚗𝚍 𝚒𝚝 𝚠𝚒𝚕𝚕 𝚋𝚎 𝚞𝚜𝚎𝚏𝚞𝚕 𝚝𝚘 𝚢𝚘𝚞𝚛 𝚙𝚎𝚎𝚛𝚜.</p><p>𝙻𝚎𝚝 𝚖𝚎 𝚔𝚗𝚘𝚠 𝚒𝚏 𝚢𝚘𝚞 𝚑𝚊𝚟𝚎 𝚊𝚗𝚢𝚝𝚑𝚒𝚗𝚐 𝚝𝚘 𝚊𝚜𝚔 𝚒𝚗 𝚌𝚘𝚖𝚖𝚎𝚗𝚝𝚜 𝚜𝚎c𝚝𝚒𝚘𝚗 :)</p><p><a href="http://itzzmeakhi.me/"><strong><em>𝚁𝚎𝚊𝚌𝚑 𝚖𝚎 𝚘𝚞𝚝 𝚑𝚎𝚛</em></strong></a><strong><em>e</em></strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fbycodegarage.typeform.com%2Fto%2FERsPUl%3Ftypeform-embed%3Doembed%26format%3Djson&amp;url=https%3A%2F%2Fbycodegarage.typeform.com%2Fto%2FERsPUl&amp;image=https%3A%2F%2Fimages.typeform.com%2Fimages%2FFYUps4mFKPYK%2Fimage%2Fdefault&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=typeform" width="900" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1c86d2983c4f454758c6656ea9a7e1b/href">https://medium.com/media/d1c86d2983c4f454758c6656ea9a7e1b/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e290a1358a6d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bycodegarage/simple-linear-regression-in-a-comprehensive-way-e290a1358a6d">Simple Linear Regression in a Comprehensive way</a> was originally published in <a href="https://medium.com/bycodegarage">#ByCodeGarage</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Encoding Categorical data in Machine Learning]]></title>
            <link>https://medium.com/bycodegarage/encoding-categorical-data-in-machine-learning-def03ccfbf40?source=rss----4826d9cea60e---4</link>
            <guid isPermaLink="false">https://medium.com/p/def03ccfbf40</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Akhil Reddy Mallidi]]></dc:creator>
            <pubDate>Wed, 24 Jul 2019 14:43:47 GMT</pubDate>
            <atom:updated>2019-09-06T04:08:19.789Z</atom:updated>
            <content:encoded><![CDATA[<h4>Most of the Machine Learning Algorithms accepts only <strong><em>Numerical data</em></strong> as input. For example <strong><em>K-Nearest neighbor Algorithm</em></strong> calculates the <strong><em>Euclidean distance</em></strong> between the two observations, of a feature. To calculate the Euclidean distance between the two observations the input that is passed should be of <strong><em>Numerical type. </em></strong>So the <strong><em>Categorical data</em></strong> must be transformed or encoded into <strong><em>Numerical typ</em>e</strong> before feeding data to an Algorithm, which in turn yields better results.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MvemrTVg_xtUlCraA63-hg.jpeg" /></figure><p><strong><em>Categorical data</em></strong> is of two types. <strong><em>Categorical data</em></strong> that are having any <em>intrinsic ordering</em> among themselves are called <strong><em>Ordinal type. Categorical data</em></strong> which don’t have any <em>intrinsic ordering</em> among themselves are called <strong><em>Nominal type</em></strong>.</p><p>Some examples of <strong><em>Nominal Categorical data</em></strong> are:</p><pre><strong>-&gt;  </strong><em>New York, New Delhi, New Jersey, England.</em><strong><br><em>-&gt;  </em></strong><em>Pen, Pencil, Eraser.</em><strong><br>-&gt;  </strong><em>Lion, Monkey, Zebra, Peacock.</em></pre><p>Some examples of <strong><em>Ordinal Categorical data</em></strong> are:</p><pre><strong>-&gt;  </strong><em>Low, Medium, High.</em><strong><br>-&gt;  </strong><em>Agree, Neutral, Disagree.</em><strong><br>-&gt;  </strong><em>Unhappy, Happy, Very Happy.</em><strong><br>-&gt;  </strong><em>Young, Old.</em></pre><p>In this story we will discuss, various techniques to encode <strong><em>Categorical data</em></strong> which is one of the step of <strong><em>Data preprocessing</em></strong> that is to be performed before feeding data to the <em>Machine Learning Models</em>.</p><p>We will be working on <a href="https://github.com/itzzmeakhi/Medium/blob/master/EncodingCategoricalData/datasets/car-data.csv"><strong><em>car’s</em></strong></a> dataset to explore various techniques of <em>Encoding Categorical data.</em></p><p><a href="https://github.com/itzzmeakhi/Medium/blob/master/EncodingCategoricalData/datasets/car-data.csv"><strong><em>Download the car’s dataset by clicking here</em></strong></a></p><p>Firstly, load all the necessary libraries required for our project. We will be loading <a href="https://www.numpy.org/"><strong><em>Numpy</em></strong></a><strong> </strong>and <a href="https://pandas.pydata.org/"><strong><em>Pandas</em></strong></a> libraries initially. Where Numpy package is for performing Mathematical operations and Pandas package is for manipulating dataset.</p><pre># Importing all the necessary libraries</pre><pre>import numpy as np<br>import pandas as pd</pre><p>The next step after importing all the basic required libraries, is to load our <em>car’s</em> dataset into <em>pandas dataframe</em> using pandas <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html"><strong><em>read_csv() </em></strong></a>method.</p><pre># Loading the dataset</pre><pre>df_car = pd.read_csv(&#39;datasets/car-data.csv&#39;)</pre><p>Let’s perform basic <strong><em>Data Exploration</em></strong> before tapping our foot directly into various techniques for encoding categorical data. Let’s start by viewing few observations of the dataset loaded using pandas <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.head.html"><strong><em>head()</em></strong></a> method.</p><pre># Viewing first few rows of data</pre><pre>df_car.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eiSiyXrwXn3okSMrJN8ynw.png" /><figcaption><strong>First few rows of car dataset that was loaded</strong></figcaption></figure><p>From the first few rows, we noticed that the dataset comprised of both <em>Numerical</em> and <em>Categorical</em> type data. Since the dataset has nearly 26 features in it, some of the columns are not visible in this step. So let’s explore in more precise manner.</p><p>To know what are all the columns the dataset comprised of, use pandas <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.columns.html"><strong><em>dataframe.columns.</em></strong></a></p><pre># Viewing the columns present in the dataset</pre><pre>df_car.columns</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cgKlh4DP0i-4EYVXD2kGDQ.png" /><figcaption><strong>Columns present in the dataset</strong></figcaption></figure><p>So from the above, there are columns like symboling, normalised-losses, make, fuel-type, aspiration, num-of-doors, body-style etc., in the dataset. Let’s see the datatype of all features in the dataset using pandas <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dtypes.html"><strong><em>dtypes</em></strong></a>.</p><pre># Datatypes of columns present in the dataset</pre><pre>df_car.dtypes</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SAOPCXezQN7D3D6i5RoIGw.png" /><figcaption><strong>Datatypes of all features in the cars dataset</strong></figcaption></figure><p>From exploring datatypes of each features in the cars dataset, we came to know that the dataset comprised of both <strong><em>Numerical</em></strong> and <strong><em>Categorical</em></strong> type.</p><p>To know more about the null values in the dataset and number of observations in the dataset use pandas <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.info.html"><strong><em>info()</em></strong></a> method which returns general information about all features in the dataset.</p><pre># General Information regarding the dataset</pre><pre>df_car.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DkCz9N4Le30OFVEJLsghcw.png" /><figcaption><strong>General Information regarding the dataset</strong></figcaption></figure><p>There are about 205 observations in the dataset and there are null values present in <em>normalized-losses, bore, stroke, horsepower, peak-rpm, price</em> columns which are <strong>Numerical</strong> type, so handling these all Numerical features are out of scope of this story. If you’re curious to know different methods to handle <strong>Missing Values</strong> in the dataset.</p><blockquote>Check out my post on <strong><em>Handling Missing Values</em></strong>- <a href="https://towardsdatascience.com/a-comprehensive-guide-on-handling-missing-values-b1257a4866d1"><strong><em>A Comprehensive guide on Handling Missing Values</em></strong></a></blockquote><p>The <strong>Categorical</strong> feature having null values in the dataset is <em>num-of-doors</em>. It has nearly <strong>2</strong> null values in it. We will be discussing the methods to handle these null values later in this story.</p><p>Since <strong><em>Numerical features </em></strong>are out of scope of this post. We will be creating a new dataframe which includes only <strong><em>Categorical features </em></strong>using pandas <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.select_dtypes.html"><strong><em>select_dtypes()</em></strong></a> method and viewing first fews rows of new dataframe.</p><pre># Including columns which are of object datatype in modified dataframe</pre><pre>df_car_mod = df_car.select_dtypes(include=[&#39;object&#39;])</pre><pre># Viewing first few rows of data</pre><pre>df_car_mod.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AkSAS7AWtgKd_q3PXA5A3g.png" /><figcaption><strong>First few rows of new dataframe</strong></figcaption></figure><p>Checking for null values in the modified dataframe using pandas <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.isnull.html"><strong><em>isnull()</em></strong></a> method. It returns a boolean value as <strong>TRUE</strong> if any <em>Null values</em> are present and as <strong>FALSE</strong> if it is a <em>Non-Null</em> value.</p><pre># Checking for any null values present in the dataset</pre><pre>df_car_mod.isnull().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*nx0ZpP9DxNyuDJtiU1yTaQ.png" /><figcaption><strong>Number of Null values in the modified dataframe</strong></figcaption></figure><p>There are only two null values in <em>num-of-doors </em>feature in the modified dataframe. Null values in the Categorical features can be handled in two ways. One is imputing the most frequent value and the another is predicting the missing value by training the Machine Learning models like Classification, Regression etc with available data. To know more about Handling Missing values check out my <a href="https://towardsdatascience.com/a-comprehensive-guide-on-handling-missing-values-b1257a4866d1"><strong><em>post</em></strong></a><strong><em>.</em></strong></p><p>Now we are imputing those 2 <em>Missing Values</em> with the <em>Most Frequent value</em> in the <em>num-of-doors</em> column using pandas <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.fillna.html"><strong><em>fillna()</em></strong></a> method.</p><pre># Replacing null values with most frequent value</pre><pre>df_car_mod[&#39;num-of-doors&#39;] = df_car_mod[&#39;num-of-doors&#39;].fillna(df_car_mod[&#39;num-of-doors&#39;].value_counts().index[0])</pre><p>After imputing all the <em>Null values</em> with the <em>Most Frequent value</em>, checking for any null values in the dataframe.</p><pre># Checking for null values</pre><pre>df_car_mod[&#39;num-of-doors&#39;].isnull().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*2jigWZhwCWUjnqhMvJE9dg.png" /><figcaption><strong>Number of null values in the num-of-doors column</strong></figcaption></figure><blockquote><strong>Pandas get_dummies()</strong></blockquote><p>This is one of the approach and also an each one to encode <strong>Categorical</strong> data. pandas <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.get_dummies.html"><strong><em>get_dummies()</em></strong></a><strong><em> </em></strong>method takes categorical feature as an argument. Then it creates a <strong><em>Dummy Variable</em></strong> for every label in the feature, such that each dummy variable holds data as 1 or 0. 1 indicates the presence of a particular label and 0 indicates the absence of a particular label.</p><p>For example, if a feature contains labels as Male and Female. After applying pandas <em>get_dummies() </em>to that feature, Dummy variable for both Male and Female labels are created. <em>i.e., Dummy variables are created for every label in the feature. </em>So that those Dummy variables holds 1 in the presence of that label and as 0 in the absence of that label.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*4yw0rLTZKgWJPJbRRU5SCg.png" /><figcaption><strong>Sample data</strong></figcaption></figure><p>Now we are applying pandas <em>get_dummies() </em>to <em>fuel-type</em> feature in the dataframe.</p><pre># Value counts for fuel_type</pre><pre>df_car_mod[&#39;fuel-type&#39;].value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*_N23swgO9swmtnFn-b6Pxw.png" /><figcaption><strong>Value counts for fuel-type feature</strong></figcaption></figure><pre># Encoding fuel_type using get_dummies</pre><pre>df_car_mod = pd.get_dummies(df_car_mod, columns=[&#39;fuel-type&#39;], drop_first=True)</pre><blockquote>In the above code snippet, we passed an argument <strong><em>drop_first=True</em></strong>, this indicates it drops one Dummy Variable from all the dummy variables created for a feature. It is to be dropped because it causes Dummy variable Trap, which is called as some of the features are highly correlated which results in predicting of another feature. So to avoid this situation, we are dropping one dummy variable created after encoding.</blockquote><p>Let us view few rows of data after encoding <em>fuel-type</em> column using pandas <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sample.html"><strong><em>sample()</em></strong></a> method.</p><pre># Few rows of encoded data</pre><pre>df_car_mod.sample(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*zBHEFgqf5XLeVQyUIY1Yug.png" /><figcaption><strong>Few rows of encoded data</strong></figcaption></figure><p>So <em>get_dummies()</em> created an column <em>fuel-type_gas, </em>which holds data as 1 if it is gas and as 0 if it is diesel. Since we have dropped one column to avoid dummy variable trap, only one feature <em>fuel-type_gas</em> has been created.</p><blockquote><strong>Find / Replace</strong></blockquote><p>Another simplest way to encode <strong><em>Ordinal Categorical data</em></strong>, is to find the replace the value for each label, that should satisfy the intrinsic ordering among them.</p><p>Let’s replace the values in the <em>num-of-doors </em>feature using pandas <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.replace.html"><strong><em>replace()</em></strong></a><strong><em> </em></strong>method.</p><pre>## Find and Replace value in the dataset<br># Value counts for num-of-doors column</pre><pre>df_car_mod[&#39;num-of-doors&#39;].value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*EbZjYFUbWFHWhI1rPOAL8g.png" /><figcaption><strong>Value counts for num-of-doors column</strong></figcaption></figure><p>So there are only two labels in the <em>num-of-doors</em> columns. Such that there is an intrinsic ordering among themselves as four &gt; two. So replacing four as 4 and two as 2 (4&gt;2).</p><pre># Replacing values in num-of-doors column</pre><pre>df_car_mod[&#39;num-of-doors&#39;] = df_car_mod[&#39;num-of-doors&#39;].replace(&#39;four&#39;, 4)<br>df_car_mod[&#39;num-of-doors&#39;] = df_car_mod[&#39;num-of-doors&#39;].replace(&#39;two&#39;, 2)</pre><p>Let’s check the <em>num-of-doors</em> feature after replacing the values.</p><pre># Value counts for num-of-doors column</pre><pre>df_car_mod[&#39;num-of-doors&#39;].value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*c71bCKN17XbSWOpJbqT_cg.png" /><figcaption><strong>Value counts for num-of-doors column</strong></figcaption></figure><p>If there are more number of labels in the feature to replace, then we can create a dictionary with keys a labels and can pass to the pandas <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.replace.html"><strong><em>replace()</em></strong></a><strong><em> </em></strong>method.</p><pre># Create a dictionary to find and replace values</pre><pre>dic_to_replace = {&quot;num-of-doors&quot;: {&quot;four&quot;: 4, &quot;two&quot;: 2}}</pre><pre>df_car_mod.replace(dic_to_replace, inplace=True)</pre><pre># View first few rows of data</pre><pre>df_car_mod[&#39;num-of-doors&#39;].head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*T3pB2SMT69zXDqOrnWIWlw.png" /><figcaption><strong>First few rows of num-of-doors feature data</strong></figcaption></figure><blockquote><strong>Label Encoder</strong></blockquote><p><a href="https://scikit-learn.org/stable/"><strong><em>Scikit Learn</em></strong></a> provides a lot of Encoders and Transformers, to encode Categorical data. One of those encoders is <a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelEncoder.html"><strong><em>Label Encoder</em></strong></a><em>, </em>which assigns a unique value or number to each label in the feature. Let’s start encoding make feature using <em>Label Encoder</em>.</p><pre># Using SciKit Learn<br># Encoding make column using LabelEncoder</pre><pre>from sklearn.preprocessing import LabelEncoder</pre><pre>labelencoder = LabelEncoder()</pre><pre>df_car_mod[&#39;make_encoded&#39;] = labelencoder.fit_transform(df_car_mod[&#39;make&#39;])</pre><pre># Viewing few rows of make and its encoded columns</pre><pre>df_car_mod[[&#39;make&#39;, &#39;make_encoded&#39;]].sample(20)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*pKYnOXXXVGIazLyLgTLuAA.png" /><figcaption><strong>Few rows of make and make_encoded features</strong></figcaption></figure><p>From the above results when passed make feature as an argument to <em>Label Encoder , nissan </em>is encoded as 12 , <em>mazda</em> as 8 , <em>mercedes-benz</em> as 9 , <em>mitsubishi</em> as 11 and <em>toyota</em> as 19.</p><p>Unlike pandas <em>get_dummies(), Label Encoder </em>doesn’t creates any dummy variables, it encodes data into an Numerical type by assigning an unique value to each label. We can use <em>Label Encoder</em> and <em>One Hot Encoder</em> combinedly to encode data by creating dummy variables.</p><blockquote><strong>Label Binarizer</strong></blockquote><p><a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.LabelBinarizer.html"><strong><em>Label Binarizer</em></strong></a> is an <em>SciKit Learn</em> class that accepts <em>Categorical data</em> as input and returns an <em>Numpy</em> array. Unlike <em>Label Encoder</em>, it encodes the data into dummy variables indicating the presence of a particular label or not. Encoding <em>make</em> column data using <em>Label Binarizer</em>.</p><pre># Enoding make column using LabelBinarizer</pre><pre>from sklearn.preprocessing import LabelBinarizer</pre><pre>labelbinarizer = LabelBinarizer()</pre><pre>make_encoded_results = labelbinarizer.fit_transform(df_car_mod[&#39;make&#39;])</pre><p>Let’s see the Dummy variables or labels that were created after encoding with <em>Label Binarizer .</em></p><pre># Classes created in make column after encoding</pre><pre>labelbinarizer.classes_</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*ZWaWuzEWmpDAQBUEqGKXGw.png" /><figcaption><strong>Classes that were created after encoding</strong></figcaption></figure><p>Since the output from <em>Label Binarizer </em>is an<em> Numpy array, </em>we can convert numpy array to a pandas dataframe using pandas <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html"><strong><em>DataFrame()</em></strong></a> method.</p><pre># Converting an numpy array into a pandas dataframe</pre><pre>df_make_encoded = pd.DataFrame(make_encoded_results, columns=labelbinarizer.classes_)</pre><pre># Viewing few rows of data</pre><pre>df_make_encoded.sample(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WkNJni7iCQ3xufQjsWoHmQ.png" /><figcaption><strong>Few rows of encoded make column</strong></figcaption></figure><p>Now we can clearly see that every label in the make column has been created as an<em> Dummy variable</em> and they holds the data about the presence of particular label or not.</p><blockquote><strong>MultiLabel Binarizer</strong></blockquote><p><a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MultiLabelBinarizer.html"><strong><em>MultiLabel Binarizer</em></strong></a> works similar to <em>Label Binarizer</em>, but <em>MultiLabel Binarizer</em> is used when any feature containing records having <strong><em>Multi Label’s</em></strong>. Lets work with <em>Multi Label Binarizer</em> with sample data since our loaded dataset doesn’t have any records with <strong><em>Multi Label’s.</em></strong></p><pre># Creating an MultiLabel Array</pre><pre>multilabel_feature = [(&quot;New Delhi&quot;, &quot;New York&quot;),<br>                     (&quot;New York&quot;, &quot;Sydney&quot;, &quot;Hyderabad&quot;, &quot;Bangalore&quot;),<br>                     (&quot;Hyderabad&quot;, &quot;Sydney&quot;, &quot;Chennai&quot;),<br>                      (&quot;Chennai&quot;, &quot;New Delhi&quot;, &quot;Bangalore&quot;),<br>                     (&quot;Bangalore&quot;, &quot;Chennai&quot;)]</pre><pre># Printing the MultiLabel Array</pre><pre>print(multilabel_feature)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cfFpLpZOn7YdyfCwNQQyBQ.png" /><figcaption><strong>Sample data having Multi Labels</strong></figcaption></figure><p>We have created an list having multi labels in each records. Now we are instantiating the <em>MultiLabelBinarizer()</em> and will pass the data to it.</p><pre># Encoding MultiLabel data using MultiLabel Binarizer </pre><pre>from sklearn.preprocessing import MultiLabelBinarizer</pre><pre>multilabelbinarizer = MultiLabelBinarizer()</pre><pre>multilabel_encoded_results = multilabelbinarizer.fit_transform(multilabel_feature)</pre><pre># Classes created in MultiLabel data after Encoding</pre><pre>multilabelbinarizer.classes_</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*CS8iWqWndIvjU6t7YDUzfw.png" /><figcaption><strong>Classes created after encoding</strong></figcaption></figure><p>Converting the <em>numpy array</em> into a <em>pandas dataframe</em> and viewing the data.</p><pre># Converting an Numpy Array into a pandas dataframe</pre><pre>df_multilabel_data = pd.DataFrame(multilabel_encoded_results, columns=multilabelbinarizer.classes_)</pre><pre># Viewing few rows of data</pre><pre>df_multilabel_data.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*nQbV-Y-lz3LUY8Ak0xgMxA.png" /><figcaption><strong>Few rows of encoded data</strong></figcaption></figure><blockquote><strong>Ordinal Encoder</strong></blockquote><p><a href="https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OrdinalEncoder.html"><strong><em>Ordinal Encoder</em></strong></a><strong><em> </em></strong>of <em>SciKit Learn </em>is used to encode categorical data into an Ordinal Integers. That means it transforms all categorical labels in a feature into where they can have any intrinsic ordering among them. The intrinsic ordering that was present among may not be true in all cases, one of them we will be seeing as an example below. So best choice is to go for<em> replacing values </em>and not this <em>Ordinal Encoder</em>, in case of <em>Ordinal Categorical data</em>.</p><p>Let’s create an sample <em>ordinal categorical data</em> and then we will apply <em>Ordinal Encode</em>r to that data to encode that data.</p><pre># Creating an Pandas dataframe for ordinal data</pre><pre>data = {&#39;Employee Id&#39; : [112, 113, 114, 115], &#39;Income Range&#39; : [&#39;Low&#39;, &#39;High&#39;, &#39;Medium&#39;, &#39;High&#39;]}</pre><pre>df_ordinal = pd.DataFrame(data)</pre><pre># Viewing few rows of created dataframe</pre><pre>df_ordinal.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*zbCuiZh-0hEVilHgtCVPLQ.png" /><figcaption><strong>Few rows of sample dataframe</strong></figcaption></figure><pre># Encoding above ordinal data using OrdinalEncoder</pre><pre>from sklearn.preprocessing import OrdinalEncoder</pre><pre>ordinalencoder = OrdinalEncoder()</pre><pre>ordinalencoder.fit_transform(df_ordinal[[&#39;Income Range&#39;]])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*Qr_rKkIopqZNLWIOrvjb5Q.png" /><figcaption><strong>Output returned after encoding using Ordinal Encoder</strong></figcaption></figure><p>From the above two results, we can observe that Low is encoded as 0 whereas High is encoded as 1 and Medium as 2 . Where intrinsic ordeing among the original data is as High &gt; Medium &gt; Low. Trying to write the same intrinsic ordering equation with encoded values is as 1 (High) &gt; 2 (Medium) &gt; 0 (Low) which is false mathematically. So try to avoid this for<em> ordinal data.</em></p><blockquote><strong>Factorize Method</strong></blockquote><p>We can acheive the ordinal data encoding with proper ordering among themselves by creating an intrinsic ordering among labels using pandas <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/categorical.html"><strong><em>Categorical()</em></strong></a> and the converting to integers using pandas <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.factorize.html"><strong><em>factorize()</em></strong></a> method so that we can get the encoded data with proper ordering among themselves.</p><pre># Using pandas factorize method for ordinal data</pre><pre>categories = pd.Categorical(df_ordinal[&#39;Income Range&#39;], categories=[&#39;Low&#39;, &#39;Medium&#39;, &#39;High&#39;], ordered=True)</pre><pre># Order of labels set for data</pre><pre>categories</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*KDWHiOplliy7Iu9jdfBRLQ.png" /><figcaption><strong>Ordering among the labels</strong></figcaption></figure><pre># Factorizing the column data</pre><pre>labels, unique = pd.factorize(categories, sort=True)<br>df_ordinal[&#39;Income Range&#39;] = labels</pre><pre># Encoded Income Range Data</pre><pre>df_ordinal[&#39;Income Range&#39;]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*WO1PYV-l35r97IpLWqVKlQ.png" /><figcaption><strong>Encoded data using pandas factorize method</strong></figcaption></figure><p>Now we can see the original ordering retained in the encoded data such as Low encoded as 0 , Medium as 1 and High as 2 .</p><blockquote><strong>DictVectorizer</strong></blockquote><p><a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.DictVectorizer.html"><strong><em>DictVectorizer</em></strong></a><strong><em> </em></strong>of <em>Scikit Learn</em> library encodes the <em>categorical data </em>in such a way that it encodes every label in the feature into <em>Dummy variables, </em>which holds data regarding the presence of particular label or not. <strong><em>DictVectorizer</em></strong> is applicable only when data is in the form of dictonary of objects. Let’s work on sample data to encode categorical data using <em>DictVectorizer</em>. It returns <em>Numpy array</em> as an output.</p><pre># DictVectorizer for encoding data</pre><pre># Creating a dictionary for sample data</pre><pre>data_prices = [<br>    {&#39;price&#39;: 850000, &#39;rooms&#39;: 4, &#39;neighborhood&#39;: &#39;Queen Anne&#39;},<br>    {&#39;price&#39;: 700000, &#39;rooms&#39;: 3, &#39;neighborhood&#39;: &#39;Fremont&#39;},<br>    {&#39;price&#39;: 650000, &#39;rooms&#39;: 3, &#39;neighborhood&#39;: &#39;Wallingford&#39;},<br>    {&#39;price&#39;: 600000, &#39;rooms&#39;: 2, &#39;neighborhood&#39;: &#39;Fremont&#39;}<br>]</pre><pre># Encoding the data using DictVectorizer</pre><pre>from sklearn.feature_extraction import DictVectorizer</pre><pre># Instantiating the DictVectorizer object</pre><pre>dictvectorizer = DictVectorizer(sparse=False, dtype=int)</pre><pre>data_prices_encoded = dictvectorizer.fit_transform(data_prices)</pre><pre># Features names of encoded data</pre><pre>dictvectorizer.get_feature_names()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*57N0CBBJm7OI-9W7LppMxg.png" /><figcaption><strong>Classes in the Encoded data</strong></figcaption></figure><p>Converting the <em>numpy array</em> into an <em>pandas dataframe</em> and view few records to ensure that the categorical data that was passed as input is encoded or not.</p><pre># Converting encoded data into pandas dataframe</pre><pre>df_prices = pd.DataFrame(data_prices_encoded, columns=dictvectorizer.get_feature_names())</pre><pre># viewing few rows of data</pre><pre>df_prices.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*vDiIF3OwzUqKl4XTm3Fyiw.png" /><figcaption><strong>Few rows of encoded data</strong></figcaption></figure><blockquote><strong>ColumnTransformer</strong></blockquote><p><a href="https://scikit-learn.org/stable/modules/generated/sklearn.compose.ColumnTransformer.html"><strong><em>ColumnTransformer</em></strong></a><strong><em> </em></strong>of SciKit Learn will transform the columns that are passed as an argument, where to which format the data is to be transformed (type of transformer) is also passed in the argument. Type of transformers like <em>Normalizer, OneHotEncoder</em> etc. We will be using <em>OneHotEncoder</em> as transformer to encode data. Let’s encode categorical data of <em>drive-wheels</em> and <em>engine-location</em> columns in loaded dataframe using <em>ColumnTransformer</em>.</p><pre># Encoding drive-wheels and engine-location columns using ColumnTransformer and OneHotEncoder</pre><pre>from sklearn.compose import ColumnTransformer<br>from sklearn.preprocessing import OneHotEncoder</pre><pre>ctransformer = ColumnTransformer([(&quot;encoded_data&quot;, OneHotEncoder(sparse=False), [4,5]),])</pre><pre>ct_encoded_results = ctransformer.fit_transform(df_car_mod)</pre><pre># Get Feature Names of Encoded columns</pre><pre>ctransformer.get_feature_names()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*vM9RVrEXK_m7ggI2yA1Fsg.png" /><figcaption><strong>Classes present in encoded data</strong></figcaption></figure><p>Converting the <em>numpy array</em> into a <em>pandas dataframe</em> and viewing few rows of data.</p><pre># Converting the numpy array into a pandas dataframe</pre><pre>df_ct_encoded_data = pd.DataFrame(ct_encoded_results, columns=ctransformer.get_feature_names())</pre><pre># Viewing first few rows of data</pre><pre>df_ct_encoded_data.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*40sm0hDr-zN-wGw3VLfzDg.png" /><figcaption><strong>First few rows of encoded dataframe</strong></figcaption></figure><p>So that total three <em>dummy</em> <em>variables </em>are created for <em>drive-wheels</em> column. And also two <em>dummy variables </em>are created for<em> engine_location </em>column. One <em>dummy variable</em> from each are dropped to avoid <em>dummy variable trap</em>.</p><pre># Dropping dummy variables to avoid multicollinearity</pre><pre>df_ct_encoded_data.drop([&#39;encoded_data__x0_4wd&#39;, &#39;encoded_data__x1_front&#39;], inplace=True, axis=1)</pre><pre># Viewing few rows of data after dropping dummy varibles</pre><pre>df_ct_encoded_data.head()</pre><p>If a whole dataframe is encoded, then there will no issue directly it will be assigned to the dataframe itself. If only one or more than one columns are encoded as in the above step, the dataframe obtained as output and original dataframe are <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html"><strong><em>concateneted</em></strong> </a>to continue further.</p><pre># Concatenating the encoded dataframe with the original dataframe</pre><pre>df = pd.concat([df_car_mod.reset_index(drop=True), df_ct_encoded_data.reset_index(drop=True)], axis=1)</pre><pre># Dropping drive-wheels, make and engine-location columns as they are encoded</pre><pre>df.drop([&#39;drive-wheels&#39;, &#39;engine-location&#39;, &#39;make&#39;], inplace=True, axis=1)</pre><pre># Viewing few rows of data</pre><pre>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cuf0xxaAep_tB5mphCUIEw.png" /><figcaption><strong>Few rows of data in the new dataframe</strong></figcaption></figure><blockquote><strong>OneHotEncoder</strong></blockquote><p><a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html"><strong><em>OneHotEncoder</em></strong></a><strong><em> </em></strong>of <em>SciKit Learn</em> encodes <em>categorical data</em> by creating Dummy <em>variables</em> for each label in the feature that was passed as an argument. It accepts only <em>Numerical data</em> as input. So the <em>categorical data</em> that needs to be encoded is converted into <em>Numerical type</em> by using <em>LabelEncoder</em>. Then passing it to the <em>OneHotEncoder</em> object and the output will be an <em>Numpy array</em>. It was one of the most preferred method.</p><p>Let’s encode <em>categorical data</em> of <em>aspiration</em> column in the dataframe using <em>OneHotEncoder</em>.</p><pre># OneHotEncoder</pre><pre># Encoding aspiration using LabelEncoder</pre><pre>from sklearn.preprocessing import LabelEncoder</pre><pre>lenc = LabelEncoder()</pre><pre>df[&#39;aspiration&#39;] = lenc.fit_transform(df[&#39;aspiration&#39;])</pre><pre># Classes in the encoded data</pre><pre>lenc.classes_</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*XRA_H7rG7b6RIU-xIS57uw.png" /><figcaption><strong>Classes in encoded aspiration column</strong></figcaption></figure><p>The data in the <em>aspiration</em> column is converted into <em>Numerical type</em> using <em>LabelEncoder</em>. Now pass this data to the <em>OneHotEncoder</em> object.</p><pre># Encoding using OneHotEncoder</pre><pre>from sklearn.preprocessing import OneHotEncoder</pre><pre>ohe = OneHotEncoder(categorical_features=[0], sparse=False)</pre><pre>ohe_results = ohe.fit_transform(df[[&#39;aspiration&#39;]])</pre><pre># Converting OneHotEncoded results into an dataframe</pre><pre>df_ohe_results = pd.DataFrame(ohe_results, columns=lenc.classes_)</pre><pre># Viewing first few rows of data</pre><pre>df_ohe_results.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*CyFxcZGWQdcB5f78JMzTEA.png" /><figcaption><strong>First few rows of encoded aspiration dataframe</strong></figcaption></figure><blockquote>We might get DeprecationWarning as OneHotEncoder class will be removed in future and alternative to that is we can use ColumnTransformer with OneHotEncoder as transformer to encode categorical data.</blockquote><p><em>Now skipping the concatenation step by keeping the length of the post in mind.</em></p><p>We can also encode all categorical columns at one using OneHotEncoder in the following way.</p><pre># To perform OneHotEncoder for all Categorical columns<br># Categorical columns present in the dataframe</pre><pre>categorical_cols = df.columns[df.dtypes==object].tolist()</pre><pre>categorical_cols</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*HGpSRUtn_3j_4G1ULWmnSQ.png" /><figcaption><strong>Categorical columns in the dataframe</strong></figcaption></figure><p>Now pass these <em>categorical columns</em> to <em>LabelEncoder</em> to convert the data present in those columns to a <em>Numerical type</em>.</p><pre># Performing LabelEncoding for remaining all categorical features</pre><pre>from sklearn.preprocessing import LabelEncoder</pre><pre>le = LabelEncoder()</pre><pre>df[categorical_cols] = df[categorical_cols].apply(lambda col: le.fit_transform(col))</pre><pre># Viewing first few rows of data</pre><pre>df[categorical_cols].head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*EyJZT3AFuiUHNNcJr25cbQ.png" /><figcaption><strong>Few rows of data after LabelEncoding</strong></figcaption></figure><p>Now pass this three columns to <em>OneHotEncoder</em> object to get an <em>encoded numpy array </em>output.</p><pre>from sklearn.preprocessing import OneHotEncoder</pre><pre>onehotencoder = OneHotEncoder(sparse=False)</pre><pre>onehotencoder.fit_transform(df[categorical_cols])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*5Y7MniNM7IACBwva6zCw1g.png" /><figcaption><strong>Numpy array after performing OneHotEncoding</strong></figcaption></figure><blockquote>Hurrah..!! Those were the techniques for encoding <em>Categorical data</em>. By concatenating the encoded dataframe’s and original dataframe properly and also taking proper care on dummy variable trap, we can obtain the encoded dataframe. By that data we can start training machine learning models.</blockquote><p><a href="https://github.com/itzzmeakhi/Medium/tree/master/EncodingCategoricalData"><strong><em>GitHub Link of the Repository</em></strong></a>- <a href="https://github.com/itzzmeakhi/Medium/tree/master/EncodingCategoricalData">https://github.com/itzzmeakhi/Medium/tree/master/EncodingCategoricalData</a></p><blockquote>Let me know if you have anything to ask. Do share the story and clap it if you liked it.</blockquote><blockquote><a href="http://itzzmeakhi.me/"><strong><em>Know more about me</em></strong></a><strong><em>- </em></strong><a href="http://itzzmeakhi.me/"><strong><em>itzzmeakhi.me</em></strong></a></blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fbycodegarage.typeform.com%2Fto%2FERsPUl%3Ftypeform-embed%3Doembed%26format%3Djson&amp;url=https%3A%2F%2Fbycodegarage.typeform.com%2Fto%2FERsPUl&amp;image=https%3A%2F%2Fimages.typeform.com%2Fimages%2FFYUps4mFKPYK%2Fimage%2Fdefault&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=typeform" width="900" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1c86d2983c4f454758c6656ea9a7e1b/href">https://medium.com/media/d1c86d2983c4f454758c6656ea9a7e1b/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=def03ccfbf40" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bycodegarage/encoding-categorical-data-in-machine-learning-def03ccfbf40">Encoding Categorical data in Machine Learning</a> was originally published in <a href="https://medium.com/bycodegarage">#ByCodeGarage</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ways to styling a React Component]]></title>
            <link>https://medium.com/bycodegarage/ways-to-styling-a-react-component-62b0cd67429c?source=rss----4826d9cea60e---4</link>
            <guid isPermaLink="false">https://medium.com/p/62b0cd67429c</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Akhil Reddy Mallidi]]></dc:creator>
            <pubDate>Wed, 24 Jul 2019 14:41:38 GMT</pubDate>
            <atom:updated>2019-09-12T05:02:06.680Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ways to style a React Component</h3><h4>React Js components have become building blocks of UI these days. If your an absolute beginner to React like me, have you ever wondered how to style an React component, then this article if for you. Having the same question on my mind, I started exploring all possible ways of styling an React component. In this article, we will go through the various ways of styling a React component by developing an ToDoApp.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yx4TkBxGQFYWHTG-JPunYw.jpeg" /></figure><p>By the end of the article, we will be developing an <strong><em>ToDoApp</em></strong> using <a href="https://reactjs.org/"><strong><em>React js</em></strong></a><strong><em> . </em></strong>First we should plan our project like how many components our app should have, what are all the elements that should be there in each component. I will skip how to create an <em>React App</em>.</p><p>If you want know about how to create an <em>React App,</em> go through my previous article : <a href="https://medium.com/front-end-weekly/getting-started-with-react-for-beginners-12750dc526e0"><strong><em>Getting started with React — for Beginners</em></strong></a><strong><em>.</em></strong></p><p>Let’s have a look of our <em>ToDoApp</em>, we will get finally.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FBl6jy-PTFPQ%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DBl6jy-PTFPQ&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FBl6jy-PTFPQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/057a05ecadb8cb68e399e29371a62f65/href">https://medium.com/media/057a05ecadb8cb68e399e29371a62f65/href</a></iframe><p>To see the live version of our <em>ToDoApp, follow this link- </em><a href="http://bit.ly/react-ToDoApp"><strong><em>Link for the live version of ToDoApp.</em></strong></a></p><p><em>Strictly for PC’s, bcoz i haven’t used any bootstrap or media queries to make it align for small screen devices.</em> <em>You can play around it :)</em></p><p>Let’s get started. Initially, i have divided our <strong><em>ToDoApp</em></strong> in two main components. One for navbar and another component for handling Tasks. Our react project directory looks somewhat like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*W_NPdEammmb5ghJnUUFnmQ.png" /><figcaption><strong>Project Directory of our React App</strong></figcaption></figure><p>Now create a folder named <em>components</em> in the <em>src</em> folder. These <em>components </em>folder will hold all of our app components in it. In that components folder create two folders namely <em>Navbar</em> and <em>Tasks. A</em>nd those two folders should also contain and <em>.js</em> and <em>.css</em> files with any name you like. I will go with our Component name. It is the best practice to go with component name, so that you won’t get confused with those files while handling complex projects. Now our project looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/191/1*QTczWu92aJ8rxNA_REdkLA.png" /><figcaption><strong>Project directory of our app</strong></figcaption></figure><p>First we will develop an logic for our <em>ToDoApp</em> and then we will style our app by going through all ways of styling an <em>React component.</em></p><p>Our Navbar should contain only the name of our app. Let’s start coding it in Navbar.js in Navbar component. We will style it next section of this article.</p><pre>// path: src/components/Navbar/Navbar.js<br></pre><pre>import React, { Component } from &#39;react&#39;;</pre><pre>import &#39;./Navbar.css&#39;;</pre><pre>class Navbar extends Component {</pre><pre>    render() {</pre><pre>        return(</pre><pre>            &lt;header&gt;</pre><pre>                &lt;h1&gt; ToDoApp &lt;/h1&gt;</pre><pre>            &lt;/header&gt;</pre><pre>        )</pre><pre>    }</pre><pre>}</pre><pre>export default Navbar;</pre><p>Importing our <em>Navbar</em> component, into <em>App.js </em>and viewing it after it is being rendered.</p><pre>// path: src/App.js</pre><pre>import React, { Component } from &#39;react&#39;;</pre><pre>import Navbar from &#39;./components/Navbar/Navbar&#39;;</pre><pre>import &#39;./App.css&#39;;</pre><pre>class App extends Component {</pre><pre>    render() {<br>        return(<br>            &lt;div&gt;<br>                &lt;Navbar /&gt;<br>            &lt;/div&gt;<br>         )<br>     }<br>}</pre><pre>export default App;</pre><p>Start the development server using this command:</p><pre>npm start</pre><p>You will get output some thing like this in the browser after our <em>Navbar </em>component being rendered in the <em>App.js.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*FvWINvzj9OTv1k5XPh9D6A.png" /><figcaption><strong>Preview of our App</strong></figcaption></figure><p>Now, let’s jump to our <em>Tasks</em> component. Create an another component <em>TaskAdd, with .js and .css in it and also Tasks.js </em>and<em> Task.js </em>along<em> </em>with<em> .css</em> files in the <em>Tasks </em>component<em>. </em>Our <em>Tasks</em> component looks some what like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/173/1*-v28zfhOvzPGHySSRZi_Bw.png" /><figcaption><strong>Task component overview</strong></figcaption></figure><p>I have designed our <em>Tasks </em>component, in such a way that our App.js passes an reference of array that contains tasks remaining to <em>Tasks.js </em>which in turn maps every task in the array to <em>Task.js, </em>where<em> Task.js </em>is a functional component which will display every individual task.</p><p><em>TaskAdd </em>component will holds elements like input field and also an button, where we can get the value of the task and add it to tasks remain array after clicking that button. Let’s start coding <em>TaskAdd.js</em> component.</p><pre>//path: src/components/Tasks/TaskAdd/TaskAdd.js</pre><pre>import React, { Component } from &#39;react&#39;;</pre><pre>import &#39;./TaskAdd.css&#39;;</pre><pre>class TaskAdd extends Component {</pre><pre>render() {<br>        return(<br>            &lt;div&gt;</pre><pre>                &lt;h1&gt;Add your task here&lt;/h1&gt;<br> <br>                &lt;input type=&quot;text&quot;placeholder=&quot;Enter Task here..!!&quot;&gt;     </pre><pre>                &lt;button&gt; Add &lt;/button&gt;</pre><pre>            &lt;/div&gt;<br>        )</pre><pre>};</pre><pre>}</pre><pre>export default TaskAdd;</pre><p>Now we will be importing our <em>TaskAdd</em> component into our <em>App.js. </em>Also we will be adding an button in <em>App.js</em> after the <em>Navbar, </em>by which we will be handling the<em> Night Mode </em>and<em> Light Mode </em>of our ToDoApp<em>.</em></p><pre>// path: src/App.js</pre><pre>import React, { Component } from &#39;react&#39;;</pre><pre>import Navbar from &#39;./components/Navbar/Navbar&#39;;</pre><pre>import TaskAdd from &#39;./components/Tasks/TaskAdd/TaskAdd&#39;;</pre><pre>import &#39;./App.css&#39;;</pre><pre>class App extends Component {</pre><pre>render() {<br>        return(<br>            &lt;div&gt;<br>                &lt;Navbar /&gt;</pre><pre>                &lt;button&gt; Mode &lt;/button&gt;</pre><pre>                &lt;TaskAdd /&gt;</pre><pre>            &lt;/div&gt;<br>         )<br>     }<br>}</pre><pre>export default App;</pre><p>The preview of our <em>ToDoApp</em> looks some what like this when rendered in <em>App.js</em> component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*dki8FK3V8Vj-hxTXF2C0pw.png" /><figcaption><strong>Preview of our ToDoApp</strong></figcaption></figure><p>Let’s create a state in <em>App</em> component, where it contains <strong><em>addTask </em></strong>which will be used to store the value that was inputed by the input field,<strong><em> tasksRemain </em></strong>is an array that holds the values of tasks remaining<strong><em> </em></strong>and<strong><em> darkMode </em></strong>contains boolean value true or false, that will be triggered using<strong><em> Mode </em></strong>button.</p><pre>// path: src/App.js</pre><pre>state = {</pre><pre>    tasksRemain: [&#39;Project - X bugs&#39;, &#39;Shopping&#39;],</pre><pre>    addTask: &#39;&#39;,</pre><pre>    darkMode: false</pre><pre>};</pre><p>Here,I am hardcoding two tasks in t<em>askRemain</em> array. You can leave it empty if you want. To catch the value that was typed in the input field, we will now create a function in the App component, that handles the catching of the value that was typed.</p><pre>// path: src/App.js<br>// Assigns Value in the Input field</pre><pre>onChangeHandler = (event) =&gt; {</pre><pre>    this.setState({</pre><pre>        addTask: event.target.value</pre><pre>    });<br>}</pre><p>By triggering an event, we are assigning the task to <strong><em>addTask</em></strong> variable of the state. Now we will write a function that will push the <strong><em>addTask</em></strong> value to <strong><em>taskRemain</em></strong> array. This function will we triggered after clicking only Add button.</p><pre>// path: src/App.js<br>// Adds Task to the array</pre><pre>addTaskHandler = () =&gt; {</pre><pre>    this.setState({</pre><pre>        tasksRemain: [...this.state.tasksRemain, this.state.addTask],</pre><pre>        addTask: &#39;&#39;</pre><pre>    });</pre><pre>}</pre><p>Now pass these two functions reference to the <em>TaskAdd</em> component. So that we will trigger them when an event occurs in the <em>TaskAdd</em> component.</p><pre>// path: src/App.js</pre><pre>&lt;TaskAdd</pre><pre>    changed={this.onChangeHandler}</pre><pre>    clicked={this.addTaskHandler} /&gt;</pre><p>Now using props in <em>TaskAdd </em>component we will assign the references of these two persons to the events. <em>addTaskHandler() </em>will be triggered when an <em>onClick </em>event occurs in the button element.<em> onChangeHandler()</em> will be triggered when an <em>onChange</em> event occurs in the input field.</p><pre>//path: src/components/Tasks/TaskAdd/TaskAdd.js</pre><pre>import React, { Component } from &#39;react&#39;;</pre><pre>import &#39;./TaskAdd.css&#39;;</pre><pre>class TaskAdd extends Component {</pre><pre>render() {<br>        return(<br>            &lt;div&gt;</pre><pre>            &lt;h1&gt;Add your task here&lt;/h1&gt;</pre><pre>            &lt;input                                  <br>                type=&quot;text&quot;                     <br>                onChange={this.props.changed}   <br>                placeholder=&quot;Enter Task here..!!&quot;&gt;&lt;/input&gt; <br>                <br>            &lt;button                     <br>                onClick={this.props.clicked}&gt;        <br>                Add                <br>            &lt;/button&gt;</pre><pre>            &lt;/div&gt;<br>        )</pre><pre>};</pre><pre>}</pre><pre>export default TaskAdd;</pre><p>To display all the the tasks, that are pushed into the <em>tasksRemain</em> array. Now we will pass the reference of tasksRemain array to <em>Tasks</em> component. In <em>Tasks</em> component we will access every task in the array and pass them as individual elements to the <em>Task</em> component, where we will display every task. We are now writing an <em>removeTaskHandler(), </em>in<em> App </em>component<em> </em>which takes index value of an element as a parameter and then removes that task from the list.</p><pre>// path: src/App.js<br>// Removes tasks from the tasks array   </pre><pre>removeTaskHandler = index =&gt; {    <br>    const beforeTasks = this.state.tasksRemain.slice(0, index);<br>    const afterTasks = this.state.tasksRemain.slice(index+1); <br>    const tasks = [...beforeTasks, ...afterTasks];    <br>    //console.log(tasks);     <br>    this.setState({      tasksRemain: tasks    });  <br>}</pre><p>Now we are coding our <em>Tasks</em> component that will displays elements in the remaining tasks array.</p><pre>// path: src/components/Tasks/Tasks.js</pre><pre>import React from &#39;react&#39;;<br>import Task from &#39;./Task&#39;;<br>import &#39;./Tasks.css&#39;; </pre><pre>const Tasks=(props)=&gt; {     <br>    return (     <br>        &lt;div&gt;        <br>            &lt;h1&gt; <br>                Tasks to be completed <br>            &lt;/h1&gt;        <br>        <br>            &lt;ul&gt;         <br>            {            <br>                props.tasks.map((task, index) =&gt; {      <br>                    return (     <br>                        &lt;Task                         <br>                            remove={()=&gt;props.remove(index)}<br>                            task={task} <br>                            key={index} /&gt;                <br>                     )            <br>                 })         <br>             }         <br>             &lt;/ul&gt;     <br>         &lt;/div&gt;    <br>) }; </pre><pre>export default Tasks;</pre><p>While iterating over an array, we will have an index to each element in the array. Also we are assigning an key to the elements, because an unique value needs to there as a key for identifying every element uniquely. Task component is as follows.</p><pre>import React from &#39;react&#39;;<br>import &#39;./Task.css&#39;; <br>const Task=(props)=&gt; {    <br>    return(        <br>        &lt;li&gt;            <br>        <br>            &lt;p&gt;                 <br>                {props.task}             <br>            &lt;/p&gt;       <br>      <br>            &lt;button                            <br>                onClick={props.remove}&gt;                 <br>                Completed             <br>            &lt;/button&gt;        <br>        &lt;/li&gt;                           <br>)} </pre><pre>export default Task;</pre><p>Let’s look at our app :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*Tm7s3ODDqL33GdDAjA8pWQ.png" /><figcaption><strong>Preview of our App</strong></figcaption></figure><p>Hurrah..!! Done with the logic of our app. Let’s start styling our app. Styling can be done for a React component in four ways.</p><h4><strong>CSS Stylesheets</strong></h4><p>Like normal styling of an HTML element we can also style the elements in our React component using stylesheets. Creating classes that holds the styles that we want to render on our html element in a <em>.css file. </em>Then importing that <em>.css file </em>into our React component and initializing to the<em> className a</em>ttribute of that element will solves our problem<em>. </em>Let’s start styling the<em> Navbar </em>component of our ToDoApp.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*ehOZBUaBLB19l-naGovhIw.png" /><figcaption><strong>Preview of our app</strong></figcaption></figure><pre>//path: src/components/Navbar/Navbar.css</pre><pre>/* CSS STYLE SHEETS */ </pre><pre>header {    <br>    background-color: #38ada9;    <br>    color: #ffffff;    <br>    padding: 10px;    <br>    /*box-shadow: 5px 7px 5px 7px #888888;*/<br>}</pre><p>Here i have applied style to the html tag directly (header). So no need of initializing to the <em>className</em> attribute of that element. Just importing <em>.css file </em>into the <em>Navbar</em> component gets our job done.</p><pre>// path : src/components/Navbar/Navbar.js</pre><pre>import React, { Component } from &#39;react&#39;;<br>import &#39;./Navbar.css&#39;;  </pre><pre>class Navbar extends Component {     <br>    render() {        <br>        return(            <br>            &lt;header&gt;                <br>                &lt;h1&gt; ToDoApp &lt;/h1&gt;            <br>            &lt;/header&gt;        <br>        )    <br>     }<br>} </pre><pre>export default Navbar;</pre><p><em>Navbar</em> component part is done. Final code of <em>Navbar</em> component looks like this. Have a look of our app after applying style to <em>Navbar</em> component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*s1A6JIMqLrmI6yvMpds7Tg.jpeg" /><figcaption><strong>Preview of our app</strong></figcaption></figure><p>Now let’s apply the similar type of styling for the two sections that we have observed in above picture. Such that <em>TaskAdd</em> should be at the <strong><em>left position</em></strong>. Next to that, <strong><em>right side</em></strong> <em>Tasks</em> Remaining should be displayed. Now add the style which includes float property set to left in the <em>TaskAdd.css</em> file to meet our requirements.</p><pre>// path: src/components/Tasks/TaskAdd/TaskAdd.css</pre><pre>.task-add {    <br>    float: left;    <br>    margin: 0 auto;    <br>    padding: 70px 80px 80px 130px;<br>}</pre><p>Here we have used class, so we need to import this .css file in the component and also should be assigned to the <em>className</em> attribute of the element where we want our styled class to be triggered.</p><pre>// path: src/components/Tasks/TaskAdd/TaskAdd.js</pre><pre>import React, { Component } from &#39;react&#39;;</pre><pre>import &#39;./TaskAdd.css&#39;;</pre><pre>class TaskAdd extends Component {</pre><pre>render() {<br>        return(<br>            &lt;div className=&quot;task-add&quot;&gt;</pre><pre>            &lt;h1&gt;Add your task here&lt;/h1&gt;</pre><pre>            &lt;input                                  <br>                type=&quot;text&quot;                     <br>                onChange={this.props.changed}   <br>                placeholder=&quot;Enter Task here..!!&quot;&gt;&lt;/input&gt; <br>                <br>            &lt;button                     <br>                onClick={this.props.clicked}&gt;        <br>                Add                <br>            &lt;/button&gt;</pre><pre>            &lt;/div&gt;<br>        )</pre><pre>};</pre><pre>}</pre><pre>export default TaskAdd;</pre><p>Lets add the similar type of styling for <em>Tasks</em> components. so that all the remaining tasks will be shown at the right side of our app.</p><pre>// path: src/components/Tasks/Tasks.css<br>/* Style sheets */ </pre><pre>.task-remain {    <br>    float: right;    <br>    margin: 0 auto;    <br>    padding: 70px 150px 80px 80px;<br>}</pre><p>Now importing that <em>.css file</em> into our Tasks component. Let’s start importing now.</p><pre>import React from &#39;react&#39;;<br>import Task from &#39;./Task&#39;;<br>import &#39;./Tasks.css&#39;; </pre><pre>const Tasks=(props)=&gt; {     <br>    <br>    return (     <br>        &lt;div className=&quot;task-remain&quot;&gt;        <br>            &lt;h1&gt; Tasks to be completed &lt;/h1&gt;        <br>            &lt;ul&gt;         <br>                {            <br>                    props.tasks.map((task, index) =&gt; {         <br>                        return (    <br>                            &lt;Task                         <br>                                remove={()=&gt;props.remove(index)}  <br>                                task={task} <br>                                key={index}/&gt;                <br>                        )            <br>                     })         <br>                }         <br>           &lt;/ul&gt;     <br>       &lt;/div&gt;    <br>   ) <br>}; </pre><pre>export default Tasks;</pre><p>Let’s have a look of our ToDoApp after applying style to these two components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Ja8MUr-YK-b5aPzMXoqkA.jpeg" /><figcaption><strong>Preview of our app</strong></figcaption></figure><p>Now it looks some what pretty, when compared to previous version. Let’s add an inline style to the mode button which is highlighted in the above picture.</p><h4><strong>Inline CSS</strong></h4><p>React allows to style our component using <em>Inline CSS</em>. Attributes of normal CSS are passed as Javascript objects and assigned to the style attribute of the element we are trying to style. Since they are passed as Javascript object, CSS attributes they are written in the form of <strong><em>CamelCase . </em></strong>For example, background-color is written as backgroundColor.</p><p>Now let’s add an inline style to the Mode button in the <em>App</em> component.</p><pre>// path: src/App.js</pre><pre>import React, { Component } from &#39;react&#39;;<br>import Navbar from &#39;./components/Navbar/Navbar&#39;;<br>import Tasks from &#39;./components/Tasks/Tasks&#39;;<br>import TaskAdd from &#39;./components/Tasks/TaskAdd/TaskAdd&#39;;<br>import &#39;./App.css&#39;;</pre><pre>class App extends Component {  <br>    <br>    ......<br>    ......</pre><pre>    render() {<br>        // Button style for Dark Mode Option     <br>       <br>        let buttonStyle = {      <br>            padding: &#39;10px&#39;,      <br>            border: &#39;1px solid #000000&#39;,      <br>            borderRadius: &#39;10px&#39;,      <br>            outline: &#39;none&#39;,      <br>            display: &#39;block&#39;,      <br>            margin: &#39;10px auto&#39;,      <br>            fontSize: &#39;100%&#39;    <br>        }</pre><pre>        ....<br>        ....</pre><pre>        return (<br>        <br>        .......<br>        .......</pre><pre>        &lt;button           <br>            style={buttonStyle}&gt;           <br>            Mode         <br>        &lt;/button&gt;<br>        )<br>   }<br>}</pre><pre>export default App;</pre><p>In the similar manner, add inline styles to some remaining elements in our components. Lets add an background color to our <em>App</em> component, because it will be helpful while we are handling <strong><em>Dark Mode</em></strong> to switch colors in our app.</p><pre>// path: src/App.js</pre><pre>import React, { Component } from &#39;react&#39;;<br>import Navbar from &#39;./components/Navbar/Navbar&#39;;<br>import Tasks from &#39;./components/Tasks/Tasks&#39;;<br>import TaskAdd from &#39;./components/Tasks/TaskAdd/TaskAdd&#39;;<br>import &#39;./App.css&#39;;</pre><pre>class App extends Component {  <br>    <br>    ......<br>    ......</pre><pre>render() {<br>        // Button style for Dark Mode Option     <br>       <br>        let buttonStyle = {      <br>            padding: &#39;10px&#39;,      <br>            border: &#39;1px solid #000000&#39;,      <br>            borderRadius: &#39;10px&#39;,      <br>            outline: &#39;none&#39;,      <br>            display: &#39;block&#39;,      <br>            margin: &#39;10px auto&#39;,      <br>            fontSize: &#39;100%&#39;    <br>        }<br>       <br>        // Inline Styling for Background color     </pre><pre>        let bColor = {      <br>            backgroundColor: &#39;#ffffff&#39;,      <br>            color: &#39;#000000&#39;,      <br>            height: &#39;100vh&#39;    <br>         }</pre><pre>        ....<br>        ....</pre><pre>return (<br>        &lt;div className={bColor}&gt;<br>            .......<br>            .......</pre><pre>            &lt;button           <br>                style={buttonStyle}&gt;           <br>                Mode         <br>            &lt;/button&gt;<br>        &lt;/div&gt;</pre><pre>       )<br>   }<br>}</pre><pre>export default App;</pre><p>Similarly, add style to the <em>TaskAdd</em> component’s <em>input field, heading</em> and <em>button</em>.</p><pre>// path: src/components/Tasks/TaskAdd/TaskAdd.js</pre><pre>import React, { Component } from &#39;react&#39;;<br>import &#39;./TaskAdd.css&#39;;  </pre><pre>class TaskAdd extends Component {     <br>    render() {         </pre><pre>        let styleInput = {            <br>            padding: &#39;6px&#39;,            <br>            display: &#39;inline-block&#39;,            <br>            border: &#39;2px solid #ccc&#39;,            <br>            borderRadius: &#39;5px&#39;,            <br>            marginRight: &#39;30px&#39;,            <br>            fontSize: &#39;140%&#39;,            <br>            outline: &#39;none&#39;        <br>        };         </pre><pre>        let styleHeading = {            <br>            marginBottom: &#39;20px&#39;        <br>         }         </pre><pre>         let buttonStyle = {            <br>             padding: &#39;14px&#39;,            <br>             width: &#39;20%&#39;,            <br>             textAlign: &#39;center&#39;,            <br>             marginTop: &#39;10px&#39;,            <br>             fontWeight: &#39;bold&#39;,            <br>             backgroundColor: &#39;#74b9ff&#39;,            <br>             display: &#39;inline-block&#39;,            <br>             border: &#39;transparent&#39;,            <br>             borderRadius: &#39;5px&#39;,            <br>             fontSize: &#39;120%&#39;        <br>         }    <br>     <br>         return(             <br>             &lt;div className=&quot;task-add&quot;&gt;                 <br>                 &lt;h1                     <br>                     style={styleHeading}&gt;                     <br>                     Add your task here                 <br>                 &lt;/h1&gt;                 </pre><pre>                 &lt;input                     <br>                     style={styleInput}       <br>                     type=&quot;text&quot;                     <br>                     onChange={this.props.changed}    <br>                     placeholder=&quot;Enter Task here..!!&quot;&gt;               <br>                     &lt;/input&gt;                 </pre><pre>                 &lt;button                     <br>                     onClick={this.props.clicked}   <br>                     style={buttonStyle}&gt;            <br>                     Add                <br>                 &lt;/button&gt;            <br>              &lt;/div&gt;         <br>         )       <br>     };<br>} </pre><pre>export default TaskAdd;</pre><p>Similary add inline style to the heading and un-ordered list of the <em>Tasks </em>component.</p><pre>// path: src/components/Tasks/Tasks.js</pre><pre>import React from &#39;react&#39;;<br>import Task from &#39;./Task&#39;;<br>import &#39;./Tasks.css&#39;; </pre><pre>const Tasks=(props)=&gt; {     </pre><pre>    let styleHeader = {        <br>        marginBottom: &#39;20px&#39;    <br>    };     </pre><pre>    let styleList = {        <br>        listStyle: &#39;none&#39;    <br>    }    </pre><pre>    return (     </pre><pre>        &lt;div className=&quot;task-remain&quot;&gt;        <br>            &lt;h1 style={styleHeader}&gt; <br>                Tasks to be completed <br>            &lt;/h1&gt;        </pre><pre>            &lt;ul style={styleList}&gt;         <br>                {            <br> <br>                    props.tasks.map((task, index) =&gt; {  <br>                        return (                                         <br>                            &lt;Task                         <br>                                remove={()=&gt;props.remove(index)}                               <br>                                task={task} key={index}/&gt;                <br>                        )           <br>                    })         <br>                }         <br>            &lt;/ul&gt;     <br>        &lt;/div&gt;    <br>   ) <br>}; </pre><pre>export default Tasks;</pre><p>Similary now we are adding inline style to <em>text</em> and the <em>completed button</em> in the <em>Task</em> component.</p><pre>import React from &#39;react&#39;;<br>import &#39;./Task.css&#39;; </pre><pre>const Task=(props)=&gt; {     </pre><pre>    let styleText = {        <br>        fontSize: &#39;160%&#39;    <br>    };     </pre><pre>    let styleCompletedButton = {        <br>        backgroundColor: &#39;#00b894&#39;,        <br>        fontWeight: &#39;bold&#39;,        <br>        padding: &#39;10px&#39;,        <br>        margin: &#39;15px 0&#39;,        <br>        border: &#39;transparent&#39;,        <br>        borderRadius: &#39;5px&#39;,       <br>        outline: &#39;none&#39;,        <br>        fontSize: &#39;100%&#39;    <br>    };      </pre><pre>    return(        <br>        &lt;li&gt;            <br>            &lt;p                 <br>                style={styleText}&gt;                 <br>                {props.task}             <br>            &lt;/p&gt;             </pre><pre>            &lt;button                 <br>                style={styleCompletedButton}                <br>                onClick={props.remove}&gt;                 <br>                Completed             <br>            &lt;/button&gt;        <br>        &lt;/li&gt;                           <br>     )<br>} </pre><pre>export default Task;</pre><p>Let’s have a look of our ToDoApp after applying these inline style’s to our components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0aFpbf_7Qv31l-8ycAhjzA.png" /><figcaption><strong>Preview of our App</strong></figcaption></figure><h4>Conditional styling or Dynamic styling</h4><p>It is not a different type of styling, but React allows us to apply style to our components based on some conditionals or we can pass class names to the elements in our component dynamically. Let’s add these conditional styling to our app to make it look more prettier.</p><p>Now start with the <strong><em>dark mode</em></strong> option. When an onClick event is triggered near Mode button element in the App component, then the <em>background color</em>, <em>font color</em> and also the should display the <em>mode </em>dynamically. So that the same button can be used to turn our app into <em>dark mode</em> and can also turn our app back to<em> light mode</em>. We will do that by conditonal styling.</p><pre>// path: src/App.js</pre><pre>import React, { Component } from &#39;react&#39;;<br>import Navbar from &#39;./components/Navbar/Navbar&#39;;<br>import Tasks from &#39;./components/Tasks/Tasks&#39;;<br>import TaskAdd from &#39;./components/Tasks/TaskAdd/TaskAdd&#39;;<br>import &#39;./App.css&#39;;</pre><pre>class App extends Component {  <br>    <br>    ......<br>    ......</pre><pre>    // Handles the mode of our application   </pre><pre>    darkModeHandler = () =&gt; {    <br>        this.setState({      <br>            darkMode: !this.state.darkMode     <br>        })  <br>    }</pre><pre>    render() {</pre><pre>        // Button style for Dark Mode Option     <br>       <br>        let buttonStyle = {      <br>            padding: &#39;10px&#39;,      <br>            border: &#39;1px solid #000000&#39;,      <br>            borderRadius: &#39;10px&#39;,      <br>            outline: &#39;none&#39;,      <br>            display: &#39;block&#39;,      <br>            margin: &#39;10px auto&#39;,      <br>            fontSize: &#39;100%&#39;    <br>        }<br>       <br>        // Inline Styling for Background color</pre><pre>        let bColor = {      <br>            backgroundColor: &#39;#ffffff&#39;,      <br>            color: &#39;#000000&#39;,      <br>            height: &#39;100vh&#39;    <br>         }</pre><pre>        ....<br>        ....</pre><pre>        // Conditional Styling      <br>        if(this.state.darkMode) {      <br>            //console.log(&quot;dark&quot;)      <br>            <br>            bColor = {        <br>                backgroundColor: &#39;#2d3436&#39;,        <br>                color: &#39;#ffffff&#39;,        <br>                height: &#39;100vh&#39;      <br>            };    <br>         }</pre><pre>        return (<br>        &lt;div style={bColor}&gt;<br>            .......<br>            .......</pre><pre>            &lt;button           <br>                style={buttonStyle}<br>                onClick={this.darkModeHandler}&gt;           <br>                Mode         <br>            &lt;/button&gt;<br>        &lt;/div&gt;</pre><pre>)<br>   }<br>}</pre><pre>export default App;</pre><p>The above conditional styling changes the background color based on the boolean value <strong><em>darkMode. </em></strong><em>If it is false, light mode is triggered which is set as default. In case if it is true, if enters the conditional statement and reset the style properties in it.</em></p><p>To display the mode near the button dynamically, such that it will display Light Mode when our app is in dark mode and vice versa. We will achieve it by using <strong><em>ternary variable</em></strong>. Let’s have a look.</p><pre>// path: src/App.js</pre><pre>.....<br>.....</pre><pre>&lt;button           <br>    style={buttonStyle}<br>    onClick={this.darkModeHandler}&gt;           <br>    { this.state.darkMode ? &#39;Light&#39;: &#39;Dark&#39; } Mode<br>&lt;/button&gt;</pre><pre>.....<br>.....</pre><p>Now let’s make the button to change its color based on the <strong><em>Mode</em></strong>. We will achieve it by dynamically adding classes to the element based on some conditionals.</p><p>Create classes in the <em>App.css</em> file for <em>background color</em>,<em> bold</em> and f<em>ont-color</em> and import the .<em>css file</em> into our <em>App</em> component.</p><pre>// path: src/App.css</pre><pre>@import url(https://medium.com/&#39;https://fonts.googleapis.com/cssfamily=Shadows+Into+Light&amp;display=swap&#39;);  </pre><pre>* {  <br>    margin: 0;  <br>    padding: 0;  <br>    font-family: &#39;Shadows Into Light&#39;, cursive;  <br>    word-spacing: 2px;  letter-spacing: 1px; <br>} </pre><pre>.bold {    <br>    font-weight: bold;<br>} </pre><pre>.white-font {    <br>    color: #ffffff;<br>} </pre><pre>.black-font {    <br>    color: #000000;<br>} </pre><pre>.orange-bg {    <br>    background-color: #ff7f50;<br>} </pre><pre>.green-bg {    <br>    background-color: #b8e994;<br>}</pre><p>Here we added <em>bold</em>, <em>white-font</em>, <em>black-font</em>, <em>orange-bg</em> and also <em>green-bg</em>. Also we have imported the Google font and applied as common property. Let’s add these classes dynamically to the HTML element in our <em>App</em> component.</p><pre>/ path: src/App.js</pre><pre>import React, { Component } from &#39;react&#39;;<br>import Navbar from &#39;./components/Navbar/Navbar&#39;;<br>import Tasks from &#39;./components/Tasks/Tasks&#39;;<br>import TaskAdd from &#39;./components/Tasks/TaskAdd/TaskAdd&#39;;<br>import &#39;./App.css&#39;;</pre><pre>class App extends Component {  <br>    <br>    ......<br>    ......</pre><pre>render() {<br>    // Adding classes dynamically     </pre><pre>    let buttonClasses = []     </pre><pre>    // Pushing bold class into the array     <br>    <br>    buttonClasses.push(&#39;bold&#39;);     </pre><pre>    // Checking the Mode and dynamically pushing a CSS class     <br>    <br>    if(this.state.darkMode) {      <br>        buttonClasses.push(&#39;green-bg&#39;, &#39;black-font&#39;);         <br>        //console.log(buttonClasses);    <br>    } else {      <br>        buttonClasses.push(&#39;orange-bg&#39;, &#39;black-font&#39;);         <br>        //console.log(buttonClasses);    <br>    }</pre><pre>return (<br>        &lt;div style={bColor}&gt;<br>            .......<br>            .......<br>           <br>            &lt;button           <br>                style={buttonStyle}           <br>                onClick={this.darkModeHandler}          <br>                className={buttonClasses.join(&#39; &#39;)}&gt;          <br>                { this.state.darkMode ? &#39;Light&#39;: &#39;Dark&#39; } Mode                <br>            &lt;/button&gt;</pre><pre>      )<br>   }<br>}</pre><pre>export default App;</pre><p>Let’s have a look of our app in both modes after applying these styles to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hxvgvuE0eZqX7x627CMV7w.png" /><figcaption><strong>Preview of our App in Light Mode</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UDXWC7A5mMC6XtPIF0z-gA.png" /><figcaption><strong>Preview of our App in Dark Mode</strong></figcaption></figure><blockquote><em>We had an error in our App. Anyone observed?? It a tiny one..!!</em></blockquote><p>If every task is removed by marking it as completed, then it is showing nothing. We should add any conditional statement to which checks the length of the <em>tasksRemain</em> array. If it is zero, then it should display <em>No Tasks</em>. This will make our app more user friendly. Also add an alert type background for every task based on the mode. It makes our app to look more attractive. We will achieve this by adding classes dynamically.</p><pre>// path: src/App.css</pre><pre>....<br>....</pre><pre>.no-task-alert {    <br>    float: right;    <br>    margin: 0 auto;    <br>    font-weight: bold;    <br>    font-size: 30px;    <br>    opacity: 0.7;    <br>    border-radius: 5px;    <br>    margin: 80px 350px 0 0;    <br>    padding: 80px;<br>} </pre><pre>.dark-mode {    <br>    background-color: white;    <br>    color: black; <br>}  </pre><pre>.light-mode {    <br>    background-color: black;    <br>    color: white; <br>}</pre><pre>// path: src/App.js</pre><pre>....<br>....</pre><pre>class App extends Component {</pre><pre>    ....<br>    ....</pre><pre>    render() {<br>     <br>        ....<br>        ....<br>       <br>        let numTasks = this.state.tasksRemain.length</pre><pre>        return(<br>    <br>        ....<br>        ....</pre><pre>        { numTasks === 0 ?           <br>           <br>            &lt;p <br>                className={this.state.darkMode ? &#39;no-task-alert dark-mode&#39;:&#39;no-task-alert light-mode&#39;}&gt;           <br>                No Tasks          <br>            &lt;/p&gt; :                 </pre><pre>           &lt;Tasks             <br>               tasks={this.state.tasksRemain}             <br>               remove={this.removeTaskHandler}            <br>               darkMode={this.state.darkMode}/&gt;        <br>       }</pre><pre>        )<br>   }<br>}</pre><pre>export default App;</pre><p>Also add these alert type background styles for Task component. Here we added only for<em> No Tasks</em> indication.</p><pre>// path: src/components/Tasks/Task.css</pre><pre>....<br>....</pre><pre>.list-style {    <br>    opacity: 0.7;    <br>    border-radius: 5px;    <br>    padding: 10px;    <br>    margin-bottom: 10px; <br>}  </pre><pre>.dark-mode {    <br>    background-color: white;    <br>    color: black; <br>}  </pre><pre>.light-mode {    <br>    background-color: black;    <br>    color: white; <br>}</pre><pre>// path: src/components/Tasks/Task.js</pre><pre>....<br>....</pre><pre>return(        <br>    &lt;li className={props.darkMode ? &#39;list-style dark-mode&#39;: &#39;list-style light-mode&#39;}&gt;            <br>   <br>        &lt;p                 <br>            style={styleText}&gt;                 <br>            {props.task}             <br>        &lt;/p&gt;             </pre><pre>        &lt;button                 <br>            style={styleCompletedButton}                <br>            onClick={props.remove}&gt;                 <br>            Completed             <br>        &lt;/button&gt;        <br>    &lt;/li&gt;                           <br>)</pre><pre>....<br>....</pre><p>Tadaaa..!! We have completed styling of our app. You can have your own ToDoApp for your daily use that was developed using React. Let’s have a look of final version of our app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y887DyW4kXv8WFDOIQpVrQ.png" /><figcaption><strong>Preview of our app in Dark Mode</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-XVYjZMTq7zl8JPHQaqe-w.png" /><figcaption><strong>Preview of our App in Light Mode</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ioL6Uy6zI5eGtH4b2M3xbA.png" /><figcaption><strong>Preview of an App when there are no tasks</strong></figcaption></figure><blockquote><strong>There are three more ways to style an React component. I haven’t used in the project. But we will go through them now.</strong></blockquote><h4><strong>Styled Components</strong></h4><p><a href="https://github.com/styled-components/styled-components">Styled-components</a> is a library for React. That helps us to use component-level styles in our app, where code will be a mixture of Javascript and CSS. For using styled components in our app, we need to install it first using this command.</p><pre>npm install --save styled-components</pre><p>Styling a component using styled components looks some what like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*plFi8Zn_IWss7br-USOFPg.png" /><figcaption><strong>Component styled using Styled Components</strong></figcaption></figure><h4><strong>CSS Modules</strong></h4><p>CSS Modules is similar to styling an React component, like CSS stylesheets. In CSS Modules, the classes we had created are locally scoped. That feature we will not get in CSS external stylesheets. This helps a lot that these CSS classes won’t clash with each other or overide with another, eventhough they are declared with same name. By configuring CSS Modules, in the config folder the class names we have defined will be created something like <strong><em>[APPNAME__CLASSNAME__HASHCODE</em></strong><em> ] </em>based upon the rule we declared.</p><p><a href="https://javascriptplayground.com/css-modules-webpack-react/"><strong><em>To know more about how to configure CSS Modules go through this article</em></strong></a><strong><em>- </em></strong><a href="https://javascriptplayground.com/css-modules-webpack-react/"><strong><em>Article</em></strong></a></p><h4>Radium</h4><p><a href="https://formidable.com/open-source/radium/">Radium</a> is library for React. The only cons we had while applying Inline CSS is we can’t apply psuedo selectors or any media queries. This Radium library helps us to apply psuedo selectors and also media queries in our Javascript objects and can pass as Inline styles to our React component.</p><p>To use Radium in our project, we should install it first. Install Radium library using this command.</p><pre>npm install --save radium</pre><p>We will appy psuedo selectors to the elements somewhat like this. And we will wrap our component with Radium while exporting to apply these selectors.</p><pre>var styles = {<br>  off: { <br>    backgroundColor: ‘#FF5722’, <br>    border: 0, <br>    width: ‘20px’, <br>    height: ‘20px’, <br>    borderRadius: ‘50%’, <br>    color: ‘white’, <br>    transitionDuration: ‘.2s’, <br>    transitionTimingFunction: ‘ease-out’, <br>    transform: ‘translate(0px,0px)’, <br>    ‘:hover’: { <br>      backgroundColor: ‘#FF7043’ <br>    }, <br>   ‘:focus’: { <br>      outline: ‘none’ <br>    }, <br>  }</pre><pre>// Wrapping with Radium</pre><pre>export default Radium(App);</pre><p>We had gone through all the ways of styling an React component. There is no any particular rule that states to follow any specific type of styling. It’s one personal choice to follow a specific way of styling an React component.</p><p><a href="https://github.com/itzzmeakhi/ToDoApp/tree/master"><strong><em>Github Repository link</em></strong></a><strong><em>- </em></strong><a href="https://github.com/itzzmeakhi/ToDoApp/tree/master">https://github.com/itzzmeakhi/ToDoApp/tree/master</a></p><p><a href="http://bit.ly/react-ToDoApp"><strong><em>Live ToDoApp link</em></strong></a><strong><em> — </em></strong><a href="http://bit.ly/react-ToDoApp">http://bit.ly/react-ToDoApp</a> .</p><p><em>Strictly for PC’s, bcoz i haven’t used any bootstrap or media queries to make it align for small screen devices.</em> <em>You can play around it :)</em></p><p>If you are trying to deploy your app to Github pages, <a href="https://github.com/gitname/react-gh-pages"><strong><em>follow this guide</em></strong></a></p><p>Hope you liked this article :)</p><p><strong><em>Do share the story and clap it if you liked it.</em></strong></p><blockquote>Let me know if you have anything to ask :)</blockquote><blockquote><a href="http://itzzmeakhi.me/">Know more about me</a>- <a href="http://itzzmeakhi.me/">itzzmeakhi.me</a></blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fbycodegarage.typeform.com%2Fto%2FERsPUl%3Ftypeform-embed%3Doembed%26format%3Djson&amp;url=https%3A%2F%2Fbycodegarage.typeform.com%2Fto%2FERsPUl&amp;image=https%3A%2F%2Fimages.typeform.com%2Fimages%2FFYUps4mFKPYK%2Fimage%2Fdefault&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=typeform" width="900" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1c86d2983c4f454758c6656ea9a7e1b/href">https://medium.com/media/d1c86d2983c4f454758c6656ea9a7e1b/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62b0cd67429c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bycodegarage/ways-to-styling-a-react-component-62b0cd67429c">Ways to styling a React Component</a> was originally published in <a href="https://medium.com/bycodegarage">#ByCodeGarage</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 React — for Beginners]]></title>
            <link>https://medium.com/bycodegarage/getting-started-with-react-for-beginners-12750dc526e0?source=rss----4826d9cea60e---4</link>
            <guid isPermaLink="false">https://medium.com/p/12750dc526e0</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Akhil Reddy Mallidi]]></dc:creator>
            <pubDate>Sun, 21 Jul 2019 12:14:28 GMT</pubDate>
            <atom:updated>2019-09-06T04:07:23.346Z</atom:updated>
            <content:encoded><![CDATA[<h3>Getting started with React — for Beginners</h3><h4><strong>React.Js</strong> is a popular Javascript library which is used for building attractive User Interfaces (UI). This post is strictly for beginners who are looking for a good start for learning React Js. To get more detailed information check out the <a href="https://reactjs.org/docs/getting-started.html"><strong><em>React Js</em></strong></a> Documentation, which comes handy while developing complex applications.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bgMQYDHhJHf17dOEHtOLxg.jpeg" /></figure><p>In this article, I will go through the basic concepts of creating a simple web application by developing an basic React App in which an user can change the background colour of the web application. You can think it as an Dark Mode which is popular now a days. But here we will give four modes for a user. Check the final version of our app below, that we are developing later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*MiTVrU23ZWTAebEPKJ8VSw.gif" /><figcaption>Final Version of the App</figcaption></figure><blockquote><strong>Getting Started</strong></blockquote><p><strong><em>React Js</em></strong> is used to create both <em>Single page</em> and <em>Multi page Applications. </em>Using React Js we can develop a complex web application by simple and reusable components. For creating an React app we need a lot of dependencies. Rather than manually installing each of them, we can use <strong><em>React CLI</em></strong>, which is also developed by its developers. So that it creates an react app for us. Installing the <strong><em>create-react-app npm package.</em></strong></p><pre>npm install -g create-react-app</pre><p><em>g here indicates that we are installing create-react-app package globally.</em></p><p>Let’s start by creating an react app using <em>React CLI.</em></p><pre>create-react-app ApplicationName</pre><p>After executing the above command in Command Line Interface, it downloads and install several dependencies and then it creates an react app. You will get the screen something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*V_My2iUQ-qWkcynLsUJaHw.png" /><figcaption>Succesful creation of an React App</figcaption></figure><p>Now, try running the development server to see the output. First go into the project folder that was created and then execute this following command to start the development server.</p><pre># Go to the project folder</pre><pre>cd ApplicationName</pre><pre># Start the Development server</pre><pre>npm start</pre><p>When you are trying to start and development server, you will get something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gP72jOFxpWMlCZR81Q8aRQ.png" /><figcaption>Basic React App that was created</figcaption></figure><p>Open the project folder in any Text Editor. My favorite was Visual Studio Code. You can use Sublime Text, Brackets, Atom etc anyone you are more familiar with. Now while exploring the project directory, we will find the directories like these.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*W_NPdEammmb5ghJnUUFnmQ.png" /><figcaption>Project Directory</figcaption></figure><p><strong><em>node_modules </em></strong>is something like where we can find all the packages and dependencies were required and installed for our project.</p><p>In<strong><em> public folder, </em></strong>we will find the index.html where all our components that were created are added to the index.html file after rendering using <strong><em>index.js</em></strong> in src folder.</p><p>In <strong><em>src folder</em></strong>, we will find all the JavaScript files, and also we will create our components there.</p><p>In <strong><em>package.json</em></strong> we will find all the dependencies, that were installed. For our basic app we will see <em>react, react-dom, react-scripts</em> installed.</p><p>Now we will start editing our <strong><em>App.js. App.js</em></strong> is also a component and is called the root component from where all remaining or children components are rendered accordingly.</p><p>Remove all the code in the App.js. We will start typing our own. Components are of two types. <strong><em>Class based Components</em></strong> and <strong><em>Functional Components. </em></strong>We will create our main component in a <em>class based way</em>, since it is a traditional way of creating components in React. I will also show how to create an component in a <em>functional way.</em></p><p>We should plan our components before getting started with coding. In our target app, we have navbar section and body section. So we will be developing our app in two components.</p><p>First we should import all the packages needed to create a component. We will import react package. Our App.js component holds only navbar section. Let’s start coding.</p><pre>// Importing react package<br>import React, { Component } from &#39;react&#39;;</pre><pre>// Importing App.css file<br>import &#39;./App.css&#39;;</pre><pre>class App extends Component {</pre><pre>render() {<br>        return(<br>           &lt;div className=&quot;App&quot;&gt;</pre><pre>              &lt;header&gt;</pre><pre>                &lt;h1 class=&quot;App-header&quot;&gt; ReactApp &lt;/h1&gt;</pre><pre>              &lt;/header&gt;</pre><pre>            &lt;/div&gt;<br>         )<br>};<br>}</pre><pre># Exporting our component</pre><pre>export default App;</pre><p>In the above, our component named <em>App</em> extends the <em>Component</em> package in react. You will see the html code in the component. Actually, it’s not the html code. Its JSX code which will be rendered to html and appended to the index.html by <em>ReactDom.render()</em>, you can see that in index.js file. Unlike in HTML, there will be some differences in JSX code, class in JSX called as <em>className, </em>hence class is only of the predefined word in ES6<em>.</em></p><p>To use our component in other components, we should export our component. That was exactly we have done in the last statement.</p><p>Now styling our App.css file, to style our navbar present in the App.js component. You can get best colors for your site in <a href="https://flatuicolors.com/"><strong><em>flatui</em></strong></a> site.</p><pre>@import url(https://medium.com/&#39;https://fonts.googleapis.com/cssfamily=Caveat&amp;display=swap&#39;);</pre><pre>.App {</pre><pre>margin: 0 auto;</pre><pre>font-family: &#39;Caveat&#39;, cursive;</pre><pre>}</pre><pre>.App-header {</pre><pre>background-color: #282c34;</pre><pre>color: aliceblue;</pre><pre>margin: 0;</pre><pre>padding: 1%;</pre><pre>box-shadow: #eee;</pre><pre>}</pre><p>We imported an google font and also added an background color, box-shadow etc to our navbar. Save these two files and open the browser to view all the changes we have done. If you are not able to view, try refreshing the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jYtuENRbExGKdmaJ4-u8Tg.png" /><figcaption>Our App after making changes</figcaption></figure><p>Now, I will show how to create an functional based components. We will be using <em>ES6 Arrow function</em> to create an component.</p><pre>import React from &#39;react&#39;;</pre><pre>const person = () =&gt; {<br>    return &lt;p&gt; Hii This is functional component &lt;/p&gt;<br>};</pre><pre>export default person;</pre><p>Now we will be creating our another component. I will name it as <em>ReactComponent.</em> You can give your own name to the component but make sure it is somewhat descriptive about the component, that we are creating.</p><p>Create a folder with component name in the src folder. You can give a name of your choice. But we you will not get confused if you are naming with the component name. And create an <em>ComponentName.js</em> and <em>ComponentName.css</em> files in that folder created.</p><p>Writing our logic in ReactComponent.js to create our target app. Here also we are creating an component in a class based way.</p><pre>// Importing the react package</pre><pre>import React, { Component } from &#39;react&#39;;</pre><pre>// Importing the css file</pre><pre>import &#39;./ReactComponent.css&#39;;</pre><pre>class ReactComponent extends Component {</pre><pre>render() {<br>  return(<br>     &lt;div className=&quot;body&quot;&gt;<br>         &lt;div className=&quot;color-list&quot;&gt;</pre><pre>             &lt;h1&gt; Color  Palette &lt;/h1&gt;</pre><pre>             &lt;p&gt;</pre><pre>                 &lt;label&gt; Red &lt;/label&gt;</pre><pre>                 &lt;button&gt; Apply &lt;/button&gt;</pre><pre>             &lt;/p&gt;<br>             &lt;p&gt;</pre><pre>                 &lt;label&gt; Blue &lt;/label&gt;</pre><pre>                 &lt;button&gt; Apply &lt;/button&gt;</pre><pre>             &lt;/p&gt;<br>             &lt;p&gt;</pre><pre>                 &lt;label&gt; Yellow &lt;/label&gt;</pre><pre>                 &lt;button&gt; Apply &lt;/button&gt;</pre><pre>             &lt;/p&gt;<br>             &lt;p&gt;</pre><pre>                 &lt;label&gt; Green &lt;/label&gt;</pre><pre>                 &lt;button&gt; Apply &lt;/button&gt;</pre><pre>             &lt;/p&gt;</pre><pre>         &lt;/div&gt;</pre><pre>         &lt;div className=&quot;color-alert&quot;&gt;</pre><pre>             &lt;h1&gt; Mode &lt;/h1&gt;</pre><pre>             &lt;div className=&quot;display-mode&quot;&gt;</pre><pre>                 &lt;p&gt; Mode is Applied. &lt;/p&gt;<br>             &lt;/div&gt;</pre><pre>          &lt;/div&gt;</pre><pre>    &lt;/div&gt;</pre><pre>);</pre><pre>}</pre><pre>}</pre><pre>export default ReactComponent;</pre><p>The basic idea of our app is to select a color from the available colors and after selecting an particular color, the background should be changed to that color and it should display “X mode is Applied” in the right side of the screen. For that we created a labels and buttons for four colors and display screen to show the color applied.</p><p>Also apply the css to our JSX code in the ReactComponent.css file.</p><pre>.body {</pre><pre>    padding: 3%;</pre><pre>    font-family: &#39;Caveat&#39;, cursive;</pre><pre>    font-size: 20px;</pre><pre>    height: 81vh;</pre><pre>}</pre><pre>.body .color-list {</pre><pre>    float: left;</pre><pre>    width: 50%;</pre><pre>}</pre><pre>.body .color-list p label {</pre><pre>    width: 30%;</pre><pre>    font-size: 175%;</pre><pre>    margin: 0 10px 0 0;</pre><pre>    display: inline-block;</pre><pre>}</pre><pre>.body .color-list p button {</pre><pre>    font-family: &#39;Caveat&#39;, cursive;</pre><pre>    font-size: 125%;</pre><pre>    padding: 7px 20px;</pre><pre>    margin: 0 0 0 40px;</pre><pre>    border: transparent;</pre><pre>    background-color: #2d3436;</pre><pre>    color: #fff;</pre><pre>}</pre><pre>.body .color-alert {</pre><pre>   float: right;</pre><pre>   width: 50%;</pre><pre>}</pre><pre>.body .color-alert .display-mode {</pre><pre>   background-color: rgb(0,0,0, 0.2);</pre><pre>   height: 20vh;</pre><pre>}</pre><pre>.body .color-alert .display-mode p {</pre><pre>   font-size: 145%;</pre><pre>   padding: 50px 200px;</pre><pre>   opacity: 1;</pre><pre>}</pre><p>Call the <em>ReactComponent as </em><strong><em>&lt;ReactComponent /&gt;</em></strong><em> </em>in the <em>App.js</em> file to render at a particular position as follows.</p><pre>// Importing react package<br>import React, { Component } from &#39;react&#39;;</pre><pre>// Importing App.css file<br>import &#39;./App.css&#39;;</pre><pre>class App extends Component {</pre><pre>render() {<br>        return(<br>           &lt;div className=&quot;App&quot;&gt;</pre><pre>&lt;header&gt;</pre><pre>&lt;h1 class=&quot;App-header&quot;&gt; ReactApp &lt;/h1&gt;</pre><pre>&lt;/header&gt;</pre><pre>&lt;ReactComponent /&gt;</pre><pre>&lt;/div&gt;<br>         )<br>};<br>}</pre><pre># Exporting our component</pre><pre>export default App;</pre><p>Save these three files and open the browser to view all the changes we have done. If you are not able to view, try refreshing the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V4ml8F3Gei_mseqIIK4LRA.png" /><figcaption>Our App after making changes</figcaption></figure><p>For changing our background color, we should pass the style to the specified element as inline style. So that using <strong><em>state</em></strong>, we can modify the values inside the component. <strong><em>State</em></strong> is a pre-defined word in React, which stores the data as objects of dictionaries, where we can modify them after any particular event inside the component.</p><p>Now let’s create a state inside the Component named <em>ReactComponent</em> to apply inline style to the element and to change the color when an button is clicked.</p><pre>class ReactComponent extends Component {</pre><pre>state = {</pre><pre>   style : [</pre><pre>       { backgroundColor: &#39;#fff&#39; }</pre><pre>   ],</pre><pre>   viewAlert: [</pre><pre>      { colorApplied: &#39;No&#39;}</pre><pre>   ]</pre><pre>}</pre><pre>}</pre><p>Here style holds the color of the background color and view alert to display the color. Because we will pass the Hex code, so we wont have color name to display. So we will pass the color name along with Hex code.</p><p>To apply Javascript code in the JSX code, we will write all the JS code in { } brackets. Now we will write an JS code to our button, which calls an <strong><em>applyColorHandler() </em></strong>function, which changes the color and displays the color applied.</p><pre>&lt;button onClick={() =&gt; this.applyColorHandler(&#39;#e17055&#39;, &#39;Red&#39;)}&gt;<br>     Apply           <br>&lt;/button&gt;</pre><p>We are passing Hex code of color, and Color Applied to the <em>applyColorHandler()</em> method.</p><p>Writing our <strong><em>applyColorHandler() , </em></strong>which holds our main logic of changing our background color and shows the color applied.</p><pre>applyColorHandler = (newColor, selColor) =&gt; {</pre><pre>    //console.log(&quot;Clicked&quot;);</pre><pre>    this.setState({</pre><pre>    style : [</pre><pre>        { backgroundColor: newColor }<br>    ],</pre><pre>    viewAlert : [</pre><pre>        { colorApplied: selColor}</pre><pre>    ]</pre><pre>    })</pre><pre>}</pre><p>We are using <strong><em>setState(), </em></strong>to modify the values that are declared using the <strong><em>state.</em></strong></p><p>Apply the style to the element, where it should be rendered in the <em>ReactComponent.</em></p><pre>&lt;div style = {this.state.style[0]} className=&quot;body&quot;&gt;</pre><pre>&lt;/div&gt;</pre><p>Now, the whole <em>ReactComponent</em> looks like as follows</p><pre>import React, { Component } from &#39;react&#39;;</pre><pre>import &#39;./ReactComponent.css&#39;;</pre><pre>class ReactComponent extends Component {</pre><pre>state = {</pre><pre>    style : [</pre><pre>        { backgroundColor: &#39;#fff&#39; }</pre><pre>    ],</pre><pre>    viewAlert: [</pre><pre>        { colorApplied: &#39;No&#39;}</pre><pre>    ]</pre><pre>}<br></pre><pre>applyColorHandler = (newColor, selColor) =&gt; {</pre><pre>    //console.log(&quot;Clicked&quot;);</pre><pre>    this.setState({</pre><pre>    style : [</pre><pre>        { backgroundColor: newColor }</pre><pre>    ],</pre><pre>    viewAlert : [</pre><pre>       { colorApplied: selColor}</pre><pre>    ]</pre><pre>})</pre><pre>}</pre><pre>render() {</pre><pre>return (</pre><pre>//console.log(this.style),</pre><pre>//console.log(this.state.style[0]),</pre><pre>    &lt;div style = {this.state.style[0]} className=&quot;body&quot;&gt;</pre><pre>       &lt;div className=&quot;color-list&quot;&gt;</pre><pre>           &lt;h1&gt; Color  Palette &lt;/h1&gt;</pre><pre>           &lt;p&gt;</pre><pre>               &lt;label&gt; Red &lt;/label&gt;</pre><pre>               &lt;button onClick={() =&gt; this.applyColorHandler(&#39;#e17055&#39;, &#39;Red&#39;)}&gt; Apply &lt;/button&gt;</pre><pre>           &lt;/p&gt;<br>           &lt;p&gt;</pre><pre>               &lt;label&gt; Blue &lt;/label&gt;</pre><pre>               &lt;button onClick={() =&gt; this.applyColorHandler(&#39;#74b9ff&#39;, &#39;Blue&#39;)}&gt; Apply &lt;/button&gt;</pre><pre>           &lt;/p&gt;<br>           &lt;p&gt;</pre><pre>               &lt;label&gt; Yellow &lt;/label&gt;</pre><pre>               &lt;button onClick={() =&gt; this.applyColorHandler(&#39;#fdcb6e&#39;, &#39;Yellow&#39;)}&gt; Apply &lt;/button&gt;</pre><pre>           &lt;/p&gt;<br>           &lt;p&gt;</pre><pre>               &lt;label&gt; Green &lt;/label&gt;</pre><pre>               &lt;button onClick={() =&gt; this.applyColorHandler(&#39;#00b894&#39;, &#39;Green&#39;)}&gt; Apply &lt;/button&gt;</pre><pre>          &lt;/p&gt;</pre><pre>    &lt;/div&gt;</pre><pre>    &lt;div className=&quot;color-alert&quot;&gt;</pre><pre>        &lt;h1&gt; Mode &lt;/h1&gt;</pre><pre>        &lt;div className=&quot;display-mode&quot;&gt;</pre><pre>            &lt;p&gt; {this.state.viewAlert[0].colorApplied} Mode is Applied. &lt;/p&gt;</pre><pre>        &lt;/div&gt;</pre><pre>    &lt;/div&gt;</pre><pre>&lt;/div&gt;</pre><pre>);</pre><pre>}</pre><pre>}</pre><pre>export default ReactComponent;</pre><p>We will use state only in class based components, while in function based components we will use React Hooks to change the values inside the component.</p><p>Save all the files and refresh the page. Hurrah ..!! Our target app is now developed and now you got enough strenght about the basics of React. In my further posts, i will take on more core concepts of React.</p><p><a href="https://github.com/itzzmeakhi/Medium/tree/master/sample-react-app"><strong><em>GitHub link of the Repository-</em></strong></a><strong><em> </em></strong><a href="https://github.com/itzzmeakhi/Medium/tree/master/sample-react-app">https://github.com/itzzmeakhi/Medium/tree/master/sample-react-app</a></p><blockquote><em>Let me know if you have anything to ask. Do share the story and clap it if you liked it.</em></blockquote><blockquote><a href="http://http;//www.itzzmeakhi.me"><strong><em>Know more about me</em></strong></a>- <a href="http://www.itzzmeakhi.me/"><strong><em>itzzmeakhi.me</em></strong></a></blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fbycodegarage.typeform.com%2Fto%2FERsPUl%3Ftypeform-embed%3Doembed%26format%3Djson&amp;url=https%3A%2F%2Fbycodegarage.typeform.com%2Fto%2FERsPUl&amp;image=https%3A%2F%2Fimages.typeform.com%2Fimages%2FFYUps4mFKPYK%2Fimage%2Fdefault&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=typeform" width="900" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1c86d2983c4f454758c6656ea9a7e1b/href">https://medium.com/media/d1c86d2983c4f454758c6656ea9a7e1b/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12750dc526e0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bycodegarage/getting-started-with-react-for-beginners-12750dc526e0">Getting started with React — for Beginners</a> was originally published in <a href="https://medium.com/bycodegarage">#ByCodeGarage</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 on handling Missing Values]]></title>
            <link>https://medium.com/bycodegarage/a-comprehensive-guide-on-handling-missing-values-b1257a4866d1?source=rss----4826d9cea60e---4</link>
            <guid isPermaLink="false">https://medium.com/p/b1257a4866d1</guid>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Akhil Reddy Mallidi]]></dc:creator>
            <pubDate>Wed, 10 Jul 2019 09:05:33 GMT</pubDate>
            <atom:updated>2020-02-15T15:34:43.621Z</atom:updated>
            <content:encoded><![CDATA[<h4>Most of the real world data contains missing values. They occur due to many reasons like some observations were not recorded and corruption of data.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V03BPsK8TzyqcZtrYIiTYw.jpeg" /></figure><p>Handling missing values is important because most of the machine learning algorithms don’t support data with missing values. These missing values in the data are to be handled properly. If not, it leads to drawing inaccurate inference about the data.</p><p>Lets us look at different ways of handling missing values using both <a href="http://pandas.pydata.org/pandas-docs/version/0.24/genindex.html#R"><strong>Pandas</strong> </a>and <a href="https://scikit-learn.org/stable/"><strong>SciKit-Learn</strong></a>.</p><p>We will be working on Titanic dataset, to explore various methods of handling missing values. Let us get started.</p><p><a href="https://github.com/itzzmeakhi/Medium/blob/master/Handling-MissingValues/datasets/titanic.csv"><em>Download titanic dataset by clicking here.</em></a></p><p>First we will import all necessary libraries. Where Numpy package is for performing Mathematical operations and Pandas package is for manipulating dataset.</p><pre># Importing all necessary libraries</pre><pre>import numpy as np<br>import pandas as pd</pre><p>Now we will be loading our downloaded titanic dataset using pandas <a href="http://pandas.pydata.org/pandas-docs/version/0.24/reference/api/pandas.read_csv.html#pandas.read_csv"><strong><em>read_csv()</em></strong></a><strong><em> </em></strong>into a dataframe. And also we will be creating a copy of that dataframe, so that we will handle the Missing Values using Pandas in one dataframe and using SciKit-Learn using another.</p><pre># Loading the dataset</pre><pre>df = pd.read_csv(&#39;datasets/titanic.csv&#39;)</pre><pre># Copying the dataframe</pre><pre>new_df = df.copy()</pre><p>Let us view first few rows of data to get insights about the data using pandas <a href="http://pandas.pydata.org/pandas-docs/version/0.24/reference/api/pandas.core.groupby.GroupBy.head.html#pandas.core.groupby.GroupBy.head"><strong><em>head()</em></strong></a>.</p><pre># First few rows of data</pre><pre>df.head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GgGEuZwvBDGUde2QffIVNA.jpeg" /><figcaption><strong>First 10 rows of data from the titanic dataset</strong></figcaption></figure><p>From the first few rows, we noticed that the dataset comprises of columns like PassengerId, Survived, Pclass, Cabin ..etc, total 12 columns. Missing values (NaN ) are visible in Age and Cabin columns, by viewing first 10 rows of data. We will look into more deep about columns having missing values and no of missing values each column has later. Lets do some Data Exploration to get some insights from it.</p><p>Let’s see the dimensions of data. Dimensions mean the number of columns and the number of observations of data, the dataset comprised of. To get the dimesions of data we will be using pandas <a href="http://pandas.pydata.org/pandas-docs/version/0.24/reference/api/pandas.DataFrame.shape.html#pandas.DataFrame.shape"><strong><em>shape()</em></strong></a><strong><em>.</em></strong></p><pre># Get the dimensions of the data</pre><pre>df.shape</pre><p>By executing the pandas.shape, it returned (891, 12). It indicates that the whole dataset comprised of 891 observations and 12 columns in it.</p><p>Now let’s check the summary statistics of data using pandas<strong><em> </em></strong><a href="http://pandas.pydata.org/pandas-docs/version/0.24/reference/api/pandas.core.groupby.DataFrameGroupBy.describe.html#pandas.core.groupby.DataFrameGroupBy.describe"><strong><em>describe()</em></strong></a><strong><em> </em></strong>method<strong><em>.</em></strong></p><pre># Summary Statistics of the data</pre><pre>df.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*JnebfHJBVQ5SYX6obgSL3Q.png" /><figcaption><strong>Descriptive statistics of dataset.</strong></figcaption></figure><p>It returned descriptive statistics of all Numerical type column’s. We can view count, mean, median, max ..etc, of each numerical data type column in the dataset. By this summary statistics, we can conclude whether there are outliers present or not which effects mean. For titanic dataset there are no outliers present.</p><p>Now check the datatype of each column in the dataset using pandas <a href="http://pandas.pydata.org/pandas-docs/version/0.24/reference/api/pandas.DataFrame.dtypes.html#pandas.DataFrame.dtypes"><strong><em>dtypes</em></strong></a>.</p><pre># View the datatype of each column in the dataset</pre><pre>df.dtypes</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*pScGZTecRx8eAd78hDgunQ.png" /><figcaption><strong>Datatype of each column in the dataset</strong></figcaption></figure><p>A basic exploration of data is done. Now quickly jump into the various techniques to handle the missing values.</p><h4>Number of Missing Values in each column</h4><p>To get the number of missing values in each column, we can use pandas <a href="http://pandas.pydata.org/pandas-docs/version/0.24/reference/api/pandas.DataFrame.isnull.html#pandas.DataFrame.isnull"><strong><em>isnull()</em></strong></a> or <a href="http://pandas.pydata.org/pandas-docs/version/0.24/reference/api/pandas.DataFrame.notnull.html#pandas.DataFrame.notnull"><strong><em>notnull()</em></strong></a> methods. <strong>isnull()</strong> method returns an boolean value <strong>TRUE</strong> when null value is present whereas <strong>notnull()</strong> method returns an boolean value <strong>TRUE</strong>, if there is no null value for every observation in the data. We will add them so that it gives the no of null or non-null values in both cases.</p><pre># Number of missing values in the data</pre><pre>df.isnull().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*93aVbjW7Kg9tpmPwSxtY9Q.png" /><figcaption><strong>Null Values in each column of the dataset</strong></figcaption></figure><pre># Number of non - null values in the data</pre><pre>df.notnull().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*B59RYmozQNmSNOkekSkIig.png" /><figcaption><strong>Non-Null Values in each column</strong></figcaption></figure><p>So from the above observations, null-values are present in Age, Cabin and Embarked columns. In Age, there are about 177 null values, 687 in Cabin and 2 in Embarked. Even you get the same when we subract number of non-null values from total number of observations.</p><p>We can also get the number of non-null values of each column with it’s datatype using pandas <a href="http://pandas.pydata.org/pandas-docs/version/0.24/reference/api/pandas.DataFrame.info.html#pandas.DataFrame.info"><strong><em>info()</em></strong> </a>method.</p><pre># Number of non - null values in the data</pre><pre>df.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*rQEUO0LodI4f5MUb2MgL0Q.png" /><figcaption><strong>Non-Null Values in each column</strong></figcaption></figure><h4><strong><em>Numerical Data</em></strong></h4><p>Missing values are present in <strong><em>Age</em></strong>,<strong><em> Cabin</em></strong> and <strong><em>Embarked</em></strong> columns. <strong>Age</strong> is of <strong>Numerical</strong> Datatype and <strong><em>Cabin</em></strong>, <strong><em>Embarked</em></strong> are of <strong>Object</strong> Datatype which may be string or a character. Now we are going to look how to handle Missing Values in colums which are of Numerical Datatype.</p><p>Either a column is Numerical or Categorical, we can delete the observations having null values in the dataset or the column that is having more number of null values.</p><p>Observations that are having null values can be deleted using pandas <a href="http://pandas.pydata.org/pandas-docs/version/0.24/reference/api/pandas.DataFrame.dropna.html#pandas.DataFrame.dropna"><strong><em>dropna() </em></strong></a>method.</p><pre># Deleting rows</pre><pre>mod_df = df.dropna()</pre><pre># No of non - null values in the modified data</pre><pre>mod_df.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*ZvN-hImdXUzNxMizi4I-EA.png" /><figcaption><strong>Non-Null Values in the Modified dataset</strong></figcaption></figure><p>So there are only 183 observations in the modified dataset out of 891 observation after dropping rows having null values.</p><p>Now let’s see how to drop columns that are having maximum number of null values in them.</p><pre># Set the limit<br># Drop columns using that limit</pre><pre>limit = len(df_n) * 0.7<br>new=df_n.dropna(axis=1, thresh=limit)</pre><pre># View columns in the dataset</pre><pre>new.columns</pre><p>We have set a limit to 70 percent, so that the columns having null values more than or equal to 70 percent are dropped from the dataframe. Viewing columns to see which column in the dataset has been dropped.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*mJzRyQkgyI8glam4FnjZeQ.png" /><figcaption><strong>Columns present in the dataframe</strong></figcaption></figure><p>So from the above, we noticed that the <strong><em>Cabin</em></strong> column has been dropped. Since <strong><em>Cabin</em></strong> column consists of nearly 687 null values out of 891, which is 77.12 percent which meets our limit criteria. So <strong><em>Cabin</em></strong> columns has been dropped.</p><p>This method of deleting rows/columns is advised only when there are enough samples in the dataset. Dropping of column having more number of null values is to be done only when column deleted doesn’t effect our analysis or that column is out of scope for our model. Removing data leads to loss of information which inturn we will not the desired output while predicting.</p><blockquote><strong>Imputing with Mean/Median/Mode/Backward fill/ Forward fill</strong></blockquote><p>Null values are replaced with mean/median.mode in this method. This is the statistical method of handling Null values. This method yields good results when compared to removing null values.</p><p>The mean of the numerical column data is used to replace null values when the data is normally distributed. Median is used if the data comprised of outliers. Mode is used when the data having more occurences of a particular value or more frequent value.</p><p>Let’s replace null values in the <strong>Age</strong> column by <strong><em>pandas</em></strong>.</p><pre># Mean of Age column</pre><pre>df[&#39;Age&#39;].mean()<br>df[&#39;Age&#39;].median()<br>df[&#39;Age&#39;].mode()</pre><p>We have got <strong><em>mean</em></strong> as <strong>29.69, <em>median </em></strong>as <strong>28.0</strong> and <strong><em>mode</em></strong> as <strong>24.</strong>0 for <strong>Age</strong> column. Since Age column has no outliers in it, we are replacing null values with mean using pandas <a href="http://pandas.pydata.org/pandas-docs/version/0.24/reference/api/pandas.DataFrame.replace.html#pandas.DataFrame.replace"><strong><em>replace()</em></strong></a> or <a href="http://pandas.pydata.org/pandas-docs/version/0.24/reference/api/pandas.DataFrame.fillna.html#pandas.DataFrame.fillna"><strong><em>fillna()</em></strong></a> methods.</p><pre># Replace Null Values (np.nan) with mean</pre><pre>df[&#39;Age&#39;] = df[&#39;Age&#39;].replace(np.nan, df[&#39;Age&#39;].mean())</pre><pre># Alternate way to fill null values with mean</pre><pre>df[&#39;Age&#39;] = df[&#39;Age&#39;].fillna(df[&#39;Age&#39;].mean())</pre><p>Let’s check the total number of null values in the <strong>Age</strong> column</p><pre># Checking for null values in Age column</pre><pre>df[&#39;Age&#39;].isnull().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/919/1*1wp1YwM-GC0cUG0htJgWRQ.png" /><figcaption><strong>Number of null values in Age column</strong></figcaption></figure><p>We’ve got number of null values in the <strong>Age</strong> column as 0. Hence null values in Age are replaced by its mean. Wanna have a glimpse, whether they are replaced with mean or any other value start comparing any observation having null value before and after this step. We will notice that mean value is replaced in its position. Similar to that, we can also replace null values with median and mode.</p><pre># In the same way we can impute using median and mode</pre><pre>df[&#39;Age&#39;] = df[&#39;Age&#39;].replace(np.nan, df[&#39;Age&#39;].median())</pre><pre>df[&#39;Age&#39;] = df[&#39;Age&#39;].replace(np.nan, df[&#39;Age&#39;].mode())</pre><pre># Alternate ways to impute null values with median and mode</pre><pre>df[&#39;Age&#39;] = df[&#39;Age&#39;].fillna(df[&#39;Age&#39;].median())</pre><pre>df[&#39;Age&#39;] = df[&#39;Age&#39;].fillna(df[&#39;Age&#39;].mode())</pre><p>In addition to this statistical method of filling null values, we can also fill null values by it’s previous value in the column which is called <strong>Backward fill</strong> or next occurring value in the column which is called <strong>Forward fill</strong>.</p><pre># Backward fill or Forward fill can be used to impute the previous or next values</pre><pre># Backward fill</pre><pre>df[&#39;Age&#39;] = df[&#39;Age&#39;].fillna(method=&#39;bfill&#39;)</pre><pre># Forward fill</pre><pre>df[&#39;Age&#39;] = df[&#39;Age&#39;].fillna(method=&#39;ffill&#39;)</pre><p>Now let’s replace null values in <strong>Age</strong> column by <a href="https://scikit-learn.org/stable/"><strong>SciKit Learn</strong></a><strong>.</strong></p><p>Replacing null values with mean using <strong>S</strong><a href="https://scikit-learn.org/stable/"><strong>ciKit Learn’s</strong></a> <strong><em>S</em></strong><a href="https://scikit-learn.org/stable/modules/generated/sklearn.impute.SimpleImputer.html"><strong><em>impleImputer</em></strong></a> class. We can change strategy parameter as median when we want replace those null values with median.</p><pre># Replacing the null values in the Age column with Mean</pre><pre>from sklearn.impute import SimpleImputer</pre><pre>imputer = SimpleImputer(missing_values=np.nan, strategy=&#39;mean&#39;)</pre><pre># Fit and transform to the parameters</pre><pre>new_df[&#39;Age&#39;] = imputer.fit_transform(new_df[[&#39;Age&#39;]])</pre><pre># Checking for any null values</pre><pre>new_df[&#39;Age&#39;].isnull().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*_tolTCdFKU3ONzdsXkKS5w.png" /><figcaption><strong>Number of null values in Age column</strong></figcaption></figure><p>Hence, the null values are replaced with mean and no null values are present in the <strong>Age</strong> column. We can also replace them with median as follows</p><pre># Alternatively, we can replace null values with median, most frequent value and also with an constant</pre><pre># Replace with Median</pre><pre>imputer = SimpleImputer(missing_values=np.nan, strategy=&#39;median&#39;)</pre><pre>new_df[&#39;Age&#39;] = imputer.fit_transform(new_df[[&#39;Age&#39;]])</pre><p>Hence the null values in the columns which are of Numerical type are identified and handled. Now lets see different methods of handling categorical data.</p><h4><strong>Categorical Data</strong></h4><p><strong>Cabin</strong> and <strong>Embarked </strong>columns are of <strong><em>Categorical</em></strong> datatype. Now let’s see how to handle null values which are of Categorical type. View first few rows of these two columns to know which type of values these two columns comprised of in the dataframe.</p><pre># Handling Missing values in Categorical data</pre><pre>df[[&#39;Cabin&#39;,&#39;Embarked&#39;]].head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*YuADT0O3fee2MFtZhtnvjA.png" /><figcaption><strong>First few rows of data in Cabin and Embarked columns</strong></figcaption></figure><p>Number of null values both <strong><em>Cabin</em></strong> and <strong><em>Embarked</em></strong> column has in the titanic dataset.</p><pre># Number of Missing values in both the columns</pre><pre>df[[&#39;Cabin&#39;, &#39;Embarked&#39;]].isnull().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*4XLfrz9ae_Wg2VcV2mLYVQ.png" /><figcaption><strong>Number of null values in both Cabin and Embarked column</strong></figcaption></figure><p>From the above exploration of <strong><em>Cabin</em></strong> and <strong><em>Embarked</em></strong> columns, Embarked column may contain more frequent values in it. Since the values are a type of class. So replacing those null values with most frequent value among them.</p><pre># Most frequent values in the Embarked column data</pre><pre>df[&#39;Embarked&#39;].value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*XL5f6w0hsPPzkEcnMAwVGA.png" /><figcaption><strong>Value counts for Embarked column</strong></figcaption></figure><p>From the <a href="http://pandas.pydata.org/pandas-docs/version/0.24/reference/api/pandas.Series.value_counts.html#pandas.Series.value_counts"><strong><em>value_counts()</em></strong></a>, the most frequent value in the <strong>Embarked</strong> column is S. So replacing all null values in the <strong>Embarked</strong> column with most frequent value S.</p><pre># Replacing the null values with the most frequent value</pre><pre>df[&#39;Embarked&#39;] = df[&#39;Embarked&#39;].fillna(df[&#39;Embarked&#39;].value_counts().index[0])</pre><p>Let’s check the total number of null values in the <strong>Embarked</strong> column and also see the value_counts() to check whether they are replaced with S or not.</p><pre># Checking for null values in the Embarked Column</pre><pre>df[&#39;Embarked&#39;].isnull().sum()</pre><pre># Value counts for Embarked column</pre><pre>df[&#39;Embarked&#39;].value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*XK0fwcybC8K0MWvGvH6OGw.png" /><figcaption>Number of null values in Embarked column</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*vDrH3CaDioXAmFYMH7tXdw.png" /><figcaption>Value counts for Embarked column</figcaption></figure><p>We can observe that the number of null values in <strong>Embarked</strong> column is as 0, and also value_counts() for S had increased by 2. So null values in the <strong>Embarked</strong> column are replaced by most frequent value.</p><p>Another way of handling null values in the column which is of categorical type, is to add an <strong><em>Unknown</em></strong> class and replace those null values with that class.</p><pre># Replacing null values with Unknown Class</pre><pre>df[&#39;Cabin&#39;] = df[&#39;Cabin&#39;].fillna(&#39;Unknown&#39;)</pre><pre># Value counts for Cabin Column</pre><pre>df[&#39;Cabin&#39;].value_counts()</pre><pre># Checking for null values in Cabin column</pre><pre>df[&#39;Cabin&#39;].isnull().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*A3QRX5BSqAQ8dfspYpEsNQ.png" /><figcaption><strong>Value counts for Cabin column</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*qn-Jn7kFZMN2u_bH8RzyDA.png" /><figcaption><strong>Number of null values in Cabin column</strong></figcaption></figure><p>Null values in <strong>Cabin </strong>column are replaced by an <strong>Unknown</strong> class.</p><p>Now let’s see how to handle missing values in the columns which are of categorical type using <strong>SciKit Learn.</strong></p><p>Replacing null values in <strong>Embarked</strong> column with most frequent value using SciKit Learn’s <strong><em>SimpleImputer</em></strong> class.</p><pre># Replacing null values in Embarked with most frequent value</pre><pre>imputer = SimpleImputer(missing_values=np.nan, strategy=&#39;most_frequent&#39;)</pre><pre>new_df[&#39;Embarked&#39;] = imputer.fit_transform(new_df[[&#39;Embarked&#39;]])</pre><pre># Value counts for Embarked column</pre><pre>new_df[&#39;Embarked&#39;].value_counts()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*80Ovh7kxm1oiOl08oL687g.png" /><figcaption><strong>Value counts for Embarked column</strong></figcaption></figure><p>Null values in <strong>Embarked</strong> column are replaced by most frequent value using <strong><em>SimpleImputer</em></strong>.</p><p>Using SciKit Learn <strong><em>SimpleImputer</em></strong> class we can also replace a null value with a custom value. Replacing all null values in <strong>Cabin</strong> column with an <strong><em>Unknown</em></strong> class.</p><pre># Replacing null values in Cabin with Unknown class</pre><pre>imputer = SimpleImputer(missing_values=np.nan, strategy=&#39;constant&#39;, fill_value=&#39;Unknown&#39;)</pre><pre>new_df[&#39;Cabin&#39;] = imputer.fit_transform(new_df[[&#39;Cabin&#39;]])</pre><pre># Checking for null values in the Cabin column</pre><pre>new_df[&#39;Cabin&#39;].isnull().sum()</pre><pre># Value counts for Cabin column</pre><pre>new_df[&#39;Cabin&#39;].value_counts().head(5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*b1r2882QMaZ-aJF8DatwxA.png" /><figcaption><strong>Number of null values in Cabin column</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*4jls2kDg2xDsxpl2DXe2WQ.png" /><figcaption><strong>Value counts for Cabin column</strong></figcaption></figure><pre># No of non - null values in the modified dataset</pre><pre>df.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*1sURlVaqCAK9SggS8hCd8w.png" /><figcaption><strong>Number of non null values in the dataframe</strong></figcaption></figure><p>The null values in the columns which are of Categorical type are identified and replaced.</p><p>Saving the modified dataset to an <em>.csv</em> file using pandas <a href="http://pandas.pydata.org/pandas-docs/version/0.24/reference/api/pandas.DataFrame.to_csv.html#pandas.DataFrame.to_csv"><strong><em>to_csv()</em></strong> </a>method.</p><pre># Save to an csv file</pre><pre>df.to_csv(&#39;datasets/data_titanic.csv&#39;)<br>new_df.to_csv(&#39;datasets/data_titanic-new.csv&#39;)</pre><h4>Predict the Missing Values</h4><p>By using the columns or features that doesn’t have missing values, we can predict the null values in other columns using Machine Learning Algorithms like Classification algorithms, Decission Trees, Regression algorithms for both Numerical and Categorical type of data. This method may result in better accuracy.</p><p>Most of the dataset’s we will come across in real world contains null values. Those missing values are to be handled before training the model. In this story, we had gone through number of ways in which null values can be replaced.</p><p>GitHub Link- <a href="https://github.com/itzzmeakhi/Medium/tree/master/Handling-MissingValues">https://github.com/itzzmeakhi/Medium/tree/master/Handling-MissingValues</a></p><p>Let me know if you have anything to ask. Do share the story if you liked it.</p><p><a href="http://www.itzzmeakhi.me/"><strong><em>Know more about me</em></strong></a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fbycodegarage.typeform.com%2Fto%2FERsPUl%3Ftypeform-embed%3Doembed%26format%3Djson&amp;url=https%3A%2F%2Fbycodegarage.typeform.com%2Fto%2FERsPUl&amp;image=https%3A%2F%2Fimages.typeform.com%2Fimages%2FFYUps4mFKPYK%2Fimage%2Fdefault&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=typeform" width="900" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1c86d2983c4f454758c6656ea9a7e1b/href">https://medium.com/media/d1c86d2983c4f454758c6656ea9a7e1b/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1257a4866d1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bycodegarage/a-comprehensive-guide-on-handling-missing-values-b1257a4866d1">A Comprehensive guide on handling Missing Values</a> was originally published in <a href="https://medium.com/bycodegarage">#ByCodeGarage</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AR.JS: Web-AR enabled Invitation Cards]]></title>
            <link>https://medium.com/bycodegarage/ar-js-web-ar-enabled-invitation-cards-ebeaa5c0f592?source=rss----4826d9cea60e---4</link>
            <guid isPermaLink="false">https://medium.com/p/ebeaa5c0f592</guid>
            <category><![CDATA[web]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[arjs]]></category>
            <category><![CDATA[augmented-reality]]></category>
            <category><![CDATA[a-frame]]></category>
            <dc:creator><![CDATA[Akhil Reddy Mallidi]]></dc:creator>
            <pubDate>Wed, 10 Jul 2019 08:59:33 GMT</pubDate>
            <atom:updated>2019-09-06T04:09:52.420Z</atom:updated>
            <content:encoded><![CDATA[<h4>AR.js is great library with over 13K stars on Github. AR.js makes easy to develop augmented reality apps. It is based on web technologies. AR.js is built on the top of A-frame. Using AR.js we can display augmented reality content in our app using markers.</h4><p>Markers can pattern type or bar code type. In this project, we are using markers which are of pattern based. You can read more about A-frame and AR.js in their documentation.</p><p>A-frame — <a href="https://aframe.io/docs/0.9.0/introduction/">https://aframe.io/docs/0.9.0/introduction/</a></p><p>AR.js — <a href="https://github.com/jeromeetienne/AR.js/blob/master/README.md">https://github.com/jeromeetienne/AR.js/blob/master/README.md</a></p><p>Now directly skipping into the motto of the use case. Every occasion in one’s life involves inviting well wishers for the treat. Ever thought of inviting our buddies using invitation cards which are augmented reality enabled, so that they can view can view the content in more realistic way rather than normal printed card pattern. Web AR has made it more feasible since no need of application for it, we can directly go in the web app which we can deploy it any of the available free hosting site and view and enjoy the ar content.</p><p>Final version of the app can be viewed here</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F8oGbw9H7O3I%3Fstart%3D16%26feature%3Doembed%26start%3D16&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D8oGbw9H7O3I&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F8oGbw9H7O3I%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa2b087a0c4b14287d9899b601dbab79/href">https://medium.com/media/fa2b087a0c4b14287d9899b601dbab79/href</a></iframe><p>For my use case, there should be three sections in the invitation card. One should deal with the invitation video, other should deal with the count down time for the event and last one should deal with the map location.</p><p>For these three sections, I have trained three markers by using the marker training site provided by the developers of AR.js</p><p>Pattern markers can be trained using this site — <a href="https://jeromeetienne.github.io/AR.js/three.js/examples/marker-training/examples/generator.html">https://jeromeetienne.github.io/AR.js/three.js/examples/marker-training/examples/generator.html</a></p><p>Therefore using three images, I have got three marker images and three *.patt files. These *.patt files are used to detect the specific marker which we will be using in our app to display the content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nag5U9EYwKvoN8JdHRD3uQ.jpeg" /><figcaption>Three markers i’ve generated for my app</figcaption></figure><p>For every web app, the start point will be the basic html file. The basic html gist is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/139194500aef75b1e26dafd2eec22e3f/href">https://medium.com/media/139194500aef75b1e26dafd2eec22e3f/href</a></iframe><p>Now start including the latest A-frame build and AR.js , that we will be using in our project. The following gist is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa61992b33a5999be6224c112eb41f6f/href">https://medium.com/media/fa61992b33a5999be6224c112eb41f6f/href</a></iframe><p>Now define the body of our document, and create an aframe scene and define that we would like to use AR.js to create an ar scene and also initialize debugUIEnabled to false, if you don’t want to console out logs on the main screen. The following gist as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce4df205fc1a6406033b0afa40379971/href">https://medium.com/media/ce4df205fc1a6406033b0afa40379971/href</a></iframe><p>Now we will add the camera to the ar scene we have created. This camera is used to detect the markers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3d632e13fd0d1979b083b7ef929e4dc/href">https://medium.com/media/e3d632e13fd0d1979b083b7ef929e4dc/href</a></iframe><p>So, to display any media files as augmented content. We need to include all those files in a-assets. The following gist shows how to include the files in the app.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df058d7c0ba6d1da2a932197592147a6/href">https://medium.com/media/df058d7c0ba6d1da2a932197592147a6/href</a></iframe><p>I will be using an video to play, when an specific marker is made visible and an image to use an texture for count down timer and image pointing the map location. So i’m including one video and two images in a-assets is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/69d1f9e2379bc6e1ba0bcc04044dc664/href">https://medium.com/media/69d1f9e2379bc6e1ba0bcc04044dc664/href</a></iframe><p>It’s time to add marker patterns to our project document. Using a-marker we will include all those *.patt files that are used by our app to detect markers. And we will also define the content we should display inside a-marker, while an specific marker is detected. And we can perform multiple actions and can modify the content during run time by defining components. The following gist is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b96d9ddb39de9a33a419e64442489331/href">https://medium.com/media/b96d9ddb39de9a33a419e64442489331/href</a></iframe><p>Now to make our video to play when an marker is visible and pause the video when an marker is not visible, we defined the component near the video marker in the above gist i.e, video-vihandler. Now we will register that component and make it to perform necessary actions on the video. You can learn more about A-frame entities by going through their documentation. The following gist shows how video-vidhandler component is executed:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1888aa0215e5be51f0412107369dedc4/href">https://medium.com/media/1888aa0215e5be51f0412107369dedc4/href</a></iframe><p>Similar to that, near count down timer marker clock-text component is defined. The component is registered and it will get the current time and target time and calculate the difference. The setInterval function will trigger for every one second and it update the value of a-text near countdown timer marker. The following gist shows how countdown timer is executed and updated a-text value in the document.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/327d22e654a43d926ffe46b257dc5a7b/href">https://medium.com/media/327d22e654a43d926ffe46b257dc5a7b/href</a></iframe><p>Now, we are near to the completion of the project. The one thing that is left out is mappoint component, which should redirect to the specified location when clicked on the image. Thus to perform the specified click event an click event listener is added and redirected when the image is clicked. The following gist shows how mappoint-handler is executed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5387c42556336f0527c17494505305f1/href">https://medium.com/media/5387c42556336f0527c17494505305f1/href</a></iframe><p>We need to push this entire code with all the assets to any free hosting sites. So that the app will be live and we can play with the ar content. In my case, i pushed all my project folder to a github repository and enabled github pages. Finally, AR-App is live.</p><p>Hurrah..!! We are near to the completion. Now we can include all those markers in any invitation template, which is good looking and start sharing to your buddies..!! You can also include the AR App live url using QR Code in the template. My template looks as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W1Vh3YetUCkNywadfRJ_fQ.jpeg" /></figure><p>I have hosted the entire project in a GitHub Repository. You can clone the project and try it out.</p><p>GitHub Repository — <a href="https://github.com/itzzmeakhi/Invitation-AR">https://github.com/itzzmeakhi/Invitation-AR</a></p><p>Live URL — <a href="https://itzzmeakhi.github.io/Invitation-AR/">https://itzzmeakhi.github.io/Invitation-AR/</a></p><p>Let me know what you build and do share the article if you liked it :)</p><p>Know more about me — <a href="http://itzzmeakhi.me/">http://itzzmeakhi.me</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fbycodegarage.typeform.com%2Fto%2FERsPUl%3Ftypeform-embed%3Doembed%26format%3Djson&amp;url=https%3A%2F%2Fbycodegarage.typeform.com%2Fto%2FERsPUl&amp;image=https%3A%2F%2Fimages.typeform.com%2Fimages%2FFYUps4mFKPYK%2Fimage%2Fdefault&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=typeform" width="900" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1c86d2983c4f454758c6656ea9a7e1b/href">https://medium.com/media/d1c86d2983c4f454758c6656ea9a7e1b/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebeaa5c0f592" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bycodegarage/ar-js-web-ar-enabled-invitation-cards-ebeaa5c0f592">AR.JS: Web-AR enabled Invitation Cards</a> was originally published in <a href="https://medium.com/bycodegarage">#ByCodeGarage</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>