Search

What is the Use of Axios in React?

While dealing with web applications in React, the most common task is to communicate with backend servers. This is usually done via HTTP protocol.  We are all quite familiar with the very common XML Http Request interface and Fetch API, which allows us to fetch data and make HTTP requests. There is another way to communicate with the backend in React, and in this article we will learn about the awesome library known as Axios and some of the key features of Axios  that have contributed to its popularity among frontend developers. So let’s get started.What is Axios? (A little bit of history) Axios is used to communicate with the backend and it also supports the Promise API that is native to JS ES6.  It is a library which is used to make requests to an API, return data from the API, and then do things with that data in our React application. Axios is a very popular (over 78k stars on Github) HTTP client, which allows us to make HTTP  requests from the browser. Why Do We Need Axios in React? Axios allows us to communicate with APIs easily in our React apps. Though this can also be achieved by other methods like fetch or AJAX, Axios can provide a little more functionality that goes a long way with applications that use React.  Axios is a promise-based library used with Node.js and your browser to make asynchronous JavaScript HTTP requests. When we know we need to implement some promise-based asynchronous HTTP requests in our application, with JavaScript, we usually think of only jQuery’s AJAX or fetch method to get the job done. And while doing so, we are actually going against React!! Did you notice that? So, while React doesn’t care about DOM manipulation at all, why do we need jQuery for our React app? Since React is handling each and everything within its own virtual DOM, perhaps we don’t need  jQuery at all. And hence, Axios becomes a lighter-weight/optimized solution to play around with our HTTP requests. Apart from the above mentioned points, why I personally like AXIOS is because it has a very clean and precise syntax. See  the example code below: Don't worry if you are not familiar with the code, we will learn that later. Using FETCH API:   const getPostsData = () => {   fetch(‘https://jsonplaceholder.typicode.com/posts’)   .then(response => response.json())   .then(data => console.log(data))   .catch(error => console.log(error));   } }  getPostsData();Using AXIOS: const getPostsData = () => {   axios   .get("https://jsonplaceholder.typicode.com/posts")   .then(data => console.log(data.data))   .catch(error => console.log(error));   };  getPostsData();You might be thinking that there isn’t a very big difference but if we consider a POST or Delete or PUT request you can start observing the benefits of using Axios.  Prerequisites In order to use Axios with React, you’ll need the following: Install Node (v 10.7 or above). And if it is already installed, check the version by using npm -v  A React project setup with Create React App or any React boilerplate If you want to learn more about Axios library, head up to this link https://github.com/axios/axios.  Okay, now that we have spent a good amount of time in understanding Axios, let’s turn our attention on how to use Axios with React. Installing Axios In order to use Axios with React, we need to install Axios. It does not come as a native JavaScript API, so that's why we have to manually import into our project. There are many ways to install Axios. You can pick any of them based on your system environment. Open up a new terminal window, move to your project’s root directory, and run any of the following commands to add Axios to your project. Using npm: $ npm install axios  Using bower package manager: $ bower install axios  Using yarn:  $ yarn add axios  Using unpkg CDN:   <script src="https://unpkg.com/axios/dist/axios.min.js"></script>  Using jsDelivr CDN:    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>  It’s not as complicated as you  might think it’d be.  Fetching and Consuming Data with a Axios (GET-POST-DELETE) Web Applications use HTTP requests, for example, GET, POST and PUT, to communicate with APIs. Axios makes our life simple as it is easy for us now to perform these commands. In this section, we will learn how to use the Axios to make REST API calls like GET, POST  and DELETE in React App. So let’s get started. Performing GET Request with Axios Let’s create a new component named My List and hook it into the component DidMount lifecycle as shown below. After that we will fetch data with Get request by importing axios. Here we are using JSON placeholder API for fetching the dummy list data of users. import React from 'react';  import axios from 'axios';  export default class MyList extends React.Component {   state = {   persons: []   }  componentDidMount() {   axios.get(`https://jsonplaceholder.typicode.com/users`)   .then(response => { const users = response.data;   this.setState ({users});   })   }  render() {   return (   < ul >   {this.state.users.map (user => {user.name} )}   < /ul >   )   }  }In the above component named MyList, we have imported Axios first. axios.get(--URL--) is used to get a promise which will return a response object. The received data in response.data is assigned to the user's object.  We can also retrieve other Information like status code and others received with the response. Performing POST Request with Axios Now let’s create another component named AddUser for using the POST request which will add a user in the user list. (a.ka. Adding data into database) import React from 'react'; import axios from 'axios'; export default class AddUser extends React.Component {  state = {  userName: '',  }  handleChange = event => {  this.setState({ userName: event.target.value });  }  handleSubmit = event => {  event.preventDefault();  const user = {  userName: this.state.userName  };  axios.post(`https://jsonplaceholder.typicode.com/users`, { user })  .then(res => {  console.log(res);  console.log(res.data);  })[Text Wrapping Break] }  render() {  return (  <div>  <form onSubmit={this.handleSubmit}>  <label>  User Name:  <input type="text" name="name" onChange={this.handleChange}/>  </label>  <button type="submit">Add</button>  </form>  </div>  )  }  }In the above example, we have made a HTTP Post request to modify the database, which is a user list and added a new user to the database. Because we've initialized the state, in handleChange() we have updated the state when the API request returns data successfully. Performing POST Request with Axios Finally, the delete method. axios.delete is used to make a Delete request to the server. axiox.delete accepts two parameters: url and optional config.  axios.delete(url, { data: { foo: "bar" }, headers: { "Authorization": "***" } }); We can use config.data to set the request body and headers as shown in the below snippet. Consider the same component as above and modify the request as follows: handleSubmit = event => {   event.preventDefault();   axios.delete(`https://jsonplaceholder.typicode.com/users/${this.state.userName}`)   .then(res => {   console.log(res);   console.log(res.data);   })  } And you are done! — you’ve got a transformed and simplified React appSending custom headers with Axios Sending custom headers with Axios is very simple and straightforward.  It is done by passing an object containing the headers as the last argument.  See the below code reference:  const options = {   headers: {'X-Custom-Header': 'value'}  };  axios.post('/save', { a: 50 }, options);Looking at the response object When we send a request to server and it is successful, our then() callback will receive a response object which can have the following properties: data: It is the payload returned from the server. By default, Axios expects JSON and will parse this back into a JavaScript object for you. status: It is basically the HTTP code returned from the server. statusText: it refers to the HTTP status message returned by the server. headers: It contains all the headers sent back by the server. config: It has the original request configuration. request: It is the actual XMLHttpRequest object (when it is running in a browser)Looking at the error object And if there’s a problem with the request, the promise will be rejected with an error object containing at least one or few of the following properties: message: the error message text. response: the response object (if received) as described in the previous section. request: the actual XMLHttpRequest object (when running in a browser). config: the original request configuration. Features of Axios Library as per the Documentation: Automatically transforms for JSON data Axios is intelligent because it automatically converts a response to JSON, so while using Axios we usually skip the step of converting the response to JSON, unlike we do in Fetch() Transform request and response data Make HTTP requests from Node.js Make XMLHttpRequests from the browser Client-side support for protecting against XSRF Supports the Promise API Intercept request and response: HTTP interceptors are used when we need to change HTTP requests from our application to the server. Axios provides a way to intercept HTTP requests.  And hence Interceptors provide us the ability to do that without writing any extra code. Has an ability to cancel requests It has a built-in feature that provides client-side protection against cross-site request forgery. In case you want to dig in and learn more about these features, head up to the official documentation of AXIOS. MAKING MULTIPLE REQUESTS WITH AXIOS With Axios we get an ability to make multiple HTTP requests and handle them simultaneously using the axios.all() method. This method takes in an array of arguments and in return we get a single promise object that only resolves when all the arguments passed in the array have been resolved. Look at the below example, where we are making multiple requests to the GitHub api using the axios.all() method. axios.all([   axios.get('https://api.github.com/users/defunkt),   axios.get('https://api.github.com/users/evanphx)  ])  .then(response => {   console.log('Date created: ', response[0].data.created_at);   console.log('Date created: ', response[1].data.created_at);  }); What will happen in the above code is that it will make simultaneous requests to an array of arguments in parallel, return the response data and will console the created_at object from each of the API responses.  Think About Abstraction  In Axios it’s quite possible to create a base instance where we can drop the URL for our API as shown below:   const api = axios.create({ baseURL: "https://api.github.com/users/evanphx" });And then simply abstract the URL like shown:  async getPostsData() { const response = await api.get();   try {   this.setState({   posts: response.data.posts,   isLoading: false   });   } catch (error) {   this.setState({ error, isLoading: false });   }  }Shorthand Methods in Axios  You have already seen that Axios provides an easy-to-use API contract model in a compact package for most of our HTTP communication needs. Do you know that Axios has some shorthand methods for performing different HTTP requests?  Check them below:  axios.request(config) axios.get(url[, config]) axios.delete(url[, config]) axios.head(url[, config]) axios.options(url[, config]) axios.post(url[, data[, config]]) axios.put(url[, data[, config]]) axios.patch(url[, data[, config]]) Some Awesome Facts about Axios  Wondering about some cool facts about Axios? Let’s check them out! For Axios, there is no need for a browser environment. This neat simple library also works on the server-side!  And hence we can use Axios in our Node applications as well. Apart from fetching or retrieving data, with the help of Axios we can also check the token expiry while requesting data for client-side and server-side. And when the token is already expired we can call an API to get the new token and continue the previous API request.  In Axios, monitoring the upload and download progress is quite simple. How? Just set a callback in the request config as shown below, and enjoy. axios({   method: "get",   url: "/myFilePath",   responseType: "blob",   onDownloadProgress: (progressEvent) => { const percentCompleted = Math.round(   (progressEvent.loaded * 100) / progressEvent.total   );  console.log(percentCompleted)   this.setState({   loadingPercent: percentCompleted,   });   },  }).then((response) => {   alert("We are Ready!");  });Conclusion I hope this article has helped you in understanding about Axios and its usage for various features like fetching or retrieving data and handling responses.  In this article, we saw several practical examples to check the power of Axios inside a React application to create HTTP requests and handle responses. We also got an idea about why it is a better approach than a normal fetch api.  So what are you waiting for? Go ahead and give Axios a try. It will definitely make your life easier. Happy Learning.
What is the Use of Axios in React?
KnowledgeHut
KnowledgeHut

KnowledgeHut

Author

KnowledgeHut is an outcome-focused global ed-tech company. We help organizations and professionals unlock excellence through skills development. We offer training solutions under the people and process, data science, full-stack development, cybersecurity, future technologies and digital transformation verticals.

Posts by KnowledgeHut

What is the Use of Axios in React?

While dealing with web applications in React, the most common task is to communicate with backend servers. This is usually done via HTTP protocol.  We are all quite familiar with the very common XML Http Request interface and Fetch API, which allows us to fetch data and make HTTP requests. There is another way to communicate with the backend in React, and in this article we will learn about the awesome library known as Axios and some of the key features of Axios  that have contributed to its popularity among frontend developers. So let’s get started.What is Axios? (A little bit of history) Axios is used to communicate with the backend and it also supports the Promise API that is native to JS ES6.  It is a library which is used to make requests to an API, return data from the API, and then do things with that data in our React application. Axios is a very popular (over 78k stars on Github) HTTP client, which allows us to make HTTP  requests from the browser. Why Do We Need Axios in React? Axios allows us to communicate with APIs easily in our React apps. Though this can also be achieved by other methods like fetch or AJAX, Axios can provide a little more functionality that goes a long way with applications that use React.  Axios is a promise-based library used with Node.js and your browser to make asynchronous JavaScript HTTP requests. When we know we need to implement some promise-based asynchronous HTTP requests in our application, with JavaScript, we usually think of only jQuery’s AJAX or fetch method to get the job done. And while doing so, we are actually going against React!! Did you notice that? So, while React doesn’t care about DOM manipulation at all, why do we need jQuery for our React app? Since React is handling each and everything within its own virtual DOM, perhaps we don’t need  jQuery at all. And hence, Axios becomes a lighter-weight/optimized solution to play around with our HTTP requests. Apart from the above mentioned points, why I personally like AXIOS is because it has a very clean and precise syntax. See  the example code below: Don't worry if you are not familiar with the code, we will learn that later. Using FETCH API:   const getPostsData = () => {   fetch(‘https://jsonplaceholder.typicode.com/posts’)   .then(response => response.json())   .then(data => console.log(data))   .catch(error => console.log(error));   } }  getPostsData();Using AXIOS: const getPostsData = () => {   axios   .get("https://jsonplaceholder.typicode.com/posts")   .then(data => console.log(data.data))   .catch(error => console.log(error));   };  getPostsData();You might be thinking that there isn’t a very big difference but if we consider a POST or Delete or PUT request you can start observing the benefits of using Axios.  Prerequisites In order to use Axios with React, you’ll need the following: Install Node (v 10.7 or above). And if it is already installed, check the version by using npm -v  A React project setup with Create React App or any React boilerplate If you want to learn more about Axios library, head up to this link https://github.com/axios/axios.  Okay, now that we have spent a good amount of time in understanding Axios, let’s turn our attention on how to use Axios with React. Installing Axios In order to use Axios with React, we need to install Axios. It does not come as a native JavaScript API, so that's why we have to manually import into our project. There are many ways to install Axios. You can pick any of them based on your system environment. Open up a new terminal window, move to your project’s root directory, and run any of the following commands to add Axios to your project. Using npm: $ npm install axios  Using bower package manager: $ bower install axios  Using yarn:  $ yarn add axios  Using unpkg CDN:     Using jsDelivr CDN:      It’s not as complicated as you  might think it’d be.  Fetching and Consuming Data with a Axios (GET-POST-DELETE) Web Applications use HTTP requests, for example, GET, POST and PUT, to communicate with APIs. Axios makes our life simple as it is easy for us now to perform these commands. In this section, we will learn how to use the Axios to make REST API calls like GET, POST  and DELETE in React App. So let’s get started. Performing GET Request with Axios Let’s create a new component named My List and hook it into the component DidMount lifecycle as shown below. After that we will fetch data with Get request by importing axios. Here we are using JSON placeholder API for fetching the dummy list data of users. import React from 'react';  import axios from 'axios';  export default class MyList extends React.Component {   state = {   persons: []   }  componentDidMount() {   axios.get(`https://jsonplaceholder.typicode.com/users`)   .then(response => { const users = response.data;   this.setState ({users});   })   }  render() {   return (   < ul >   {this.state.users.map (user => {user.name} )}   < /ul >   )   }  }In the above component named MyList, we have imported Axios first. axios.get(--URL--) is used to get a promise which will return a response object. The received data in response.data is assigned to the user's object.  We can also retrieve other Information like status code and others received with the response. Performing POST Request with Axios Now let’s create another component named AddUser for using the POST request which will add a user in the user list. (a.ka. Adding data into database) import React from 'react'; import axios from 'axios'; export default class AddUser extends React.Component {  state = {  userName: '',  }  handleChange = event => {  this.setState({ userName: event.target.value });  }  handleSubmit = event => {  event.preventDefault();  const user = {  userName: this.state.userName  };  axios.post(`https://jsonplaceholder.typicode.com/users`, { user })  .then(res => {  console.log(res);  console.log(res.data);  })[Text Wrapping Break] }  render() {  return (        User Name:      Add      )  }  }In the above example, we have made a HTTP Post request to modify the database, which is a user list and added a new user to the database. Because we've initialized the state, in handleChange() we have updated the state when the API request returns data successfully. Performing POST Request with Axios Finally, the delete method. axios.delete is used to make a Delete request to the server. axiox.delete accepts two parameters: url and optional config.  axios.delete(url, { data: { foo: "bar" }, headers: { "Authorization": "***" } }); We can use config.data to set the request body and headers as shown in the below snippet. Consider the same component as above and modify the request as follows: handleSubmit = event => {   event.preventDefault();   axios.delete(`https://jsonplaceholder.typicode.com/users/${this.state.userName}`)   .then(res => {   console.log(res);   console.log(res.data);   })  } And you are done! — you’ve got a transformed and simplified React appSending custom headers with Axios Sending custom headers with Axios is very simple and straightforward.  It is done by passing an object containing the headers as the last argument.  See the below code reference:  const options = {   headers: {'X-Custom-Header': 'value'}  };  axios.post('/save', { a: 50 }, options);Looking at the response object When we send a request to server and it is successful, our then() callback will receive a response object which can have the following properties: data: It is the payload returned from the server. By default, Axios expects JSON and will parse this back into a JavaScript object for you. status: It is basically the HTTP code returned from the server. statusText: it refers to the HTTP status message returned by the server. headers: It contains all the headers sent back by the server. config: It has the original request configuration. request: It is the actual XMLHttpRequest object (when it is running in a browser)Looking at the error object And if there’s a problem with the request, the promise will be rejected with an error object containing at least one or few of the following properties: message: the error message text. response: the response object (if received) as described in the previous section. request: the actual XMLHttpRequest object (when running in a browser). config: the original request configuration. Features of Axios Library as per the Documentation: Automatically transforms for JSON data Axios is intelligent because it automatically converts a response to JSON, so while using Axios we usually skip the step of converting the response to JSON, unlike we do in Fetch() Transform request and response data Make HTTP requests from Node.js Make XMLHttpRequests from the browser Client-side support for protecting against XSRF Supports the Promise API Intercept request and response: HTTP interceptors are used when we need to change HTTP requests from our application to the server. Axios provides a way to intercept HTTP requests.  And hence Interceptors provide us the ability to do that without writing any extra code. Has an ability to cancel requests It has a built-in feature that provides client-side protection against cross-site request forgery. In case you want to dig in and learn more about these features, head up to the official documentation of AXIOS. MAKING MULTIPLE REQUESTS WITH AXIOS With Axios we get an ability to make multiple HTTP requests and handle them simultaneously using the axios.all() method. This method takes in an array of arguments and in return we get a single promise object that only resolves when all the arguments passed in the array have been resolved. Look at the below example, where we are making multiple requests to the GitHub api using the axios.all() method. axios.all([   axios.get('https://api.github.com/users/defunkt),   axios.get('https://api.github.com/users/evanphx)  ])  .then(response => {   console.log('Date created: ', response[0].data.created_at);   console.log('Date created: ', response[1].data.created_at);  }); What will happen in the above code is that it will make simultaneous requests to an array of arguments in parallel, return the response data and will console the created_at object from each of the API responses.  Think About Abstraction  In Axios it’s quite possible to create a base instance where we can drop the URL for our API as shown below:   const api = axios.create({ baseURL: "https://api.github.com/users/evanphx" });And then simply abstract the URL like shown:  async getPostsData() { const response = await api.get();   try {   this.setState({   posts: response.data.posts,   isLoading: false   });   } catch (error) {   this.setState({ error, isLoading: false });   }  }Shorthand Methods in Axios  You have already seen that Axios provides an easy-to-use API contract model in a compact package for most of our HTTP communication needs. Do you know that Axios has some shorthand methods for performing different HTTP requests?  Check them below:  axios.request(config) axios.get(url[, config]) axios.delete(url[, config]) axios.head(url[, config]) axios.options(url[, config]) axios.post(url[, data[, config]]) axios.put(url[, data[, config]]) axios.patch(url[, data[, config]]) Some Awesome Facts about Axios  Wondering about some cool facts about Axios? Let’s check them out! For Axios, there is no need for a browser environment. This neat simple library also works on the server-side!  And hence we can use Axios in our Node applications as well. Apart from fetching or retrieving data, with the help of Axios we can also check the token expiry while requesting data for client-side and server-side. And when the token is already expired we can call an API to get the new token and continue the previous API request.  In Axios, monitoring the upload and download progress is quite simple. How? Just set a callback in the request config as shown below, and enjoy. axios({   method: "get",   url: "/myFilePath",   responseType: "blob",   onDownloadProgress: (progressEvent) => { const percentCompleted = Math.round(   (progressEvent.loaded * 100) / progressEvent.total   );  console.log(percentCompleted)   this.setState({   loadingPercent: percentCompleted,   });   },  }).then((response) => {   alert("We are Ready!");  });Conclusion I hope this article has helped you in understanding about Axios and its usage for various features like fetching or retrieving data and handling responses.  In this article, we saw several practical examples to check the power of Axios inside a React application to create HTTP requests and handle responses. We also got an idea about why it is a better approach than a normal fetch api.  So what are you waiting for? Go ahead and give Axios a try. It will definitely make your life easier. Happy Learning.
5650
What is the Use of Axios in React?

While dealing with web applications in React, the... Read More

Install And Setup React App on Ubuntu

React is a JavaScript library for building user interfaces. It is opensource and maintained by Facebook.You can read more about React here:  https://reactjs.org/docs/getting-started.htmlIn this blog we are going to learn how to install and setup a React App on Ubuntu (version 16 and above).PrerequisitesThis blog assumes that you are using Ubuntu 16 or above versions and you have all the privileges to install the software in the machine, and also have access to the required websites mentioned in the blog.System Requirements:Ubuntu 16 or aboveMinimum 4GB RAMVisual Studio Code installed.Why should we choose React, and what are its advantages?React is built on JavaScript which makes it easier to learn and easier to use.React is component based which means we can write re-usable components. Start with small things, which you use to build bigger things, which you use to build apps.React is lightweight compared to Angular; which in turn makes your application faster to load—which is very important from the user’s point of view.React ensures faster rendering of DOM (document object model), this has been achieved by the introduction of Virtual DOM-currently, one of the benefits of using React for heavy loaded and dynamic software solutions.React has a helpful and interactive developer toolset which makes it easy to debug. React Developer Tools is a browser extension available for both Chrome and Firefox. It enables developers to observe reactive component hierarchies, discover child and parent components, and inspect their current state and props.  React uses JSX(JavaScript XML) which has HTML-like syntax, making it easy to code and understand.React has strong community support on Github, Stackoverflow and many other platforms.React is SEO friendly.There are certainly many other nice features about using React.What is Node.js?Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js is an Open Source Server Environment that is free and runs on almost all Operating Systems (Windows, Linux, Unix, Mac OS X, etc.).You can read more about Nodejs here: https://nodejs.org/en/Why do we need Nodejs for React apps?Node.js lets developers use JavaScript to develop variety of applications like network applications, command line tools, web APIs, mobile applications, web applications etc.React usually runs on Node Server in development, but we can make use of other Servers likes Apache or Nginix to run React App in production. You do not need NodeJS to run React in production.What is NPM, why do we need NPM for React apps?NPM (Node Package Manager) is a dependency management tool for JavaScript applications. It is Open Source and also has command line utility for interacting with the application that aids in package installation, version management, and dependency management.React does not ship with all the features by itself, so it uses external packages to add the required features to the React application. These packages are maintained by NPM (Node package manager) which is shipped with Nodejs in development.You can read more about npm here: https://nodejs.org/en/knowledge/getting-started/npm/what-is-npm/We can use yarn instead of NPM during development and production for React apps.Install Node.jsThere are many ways to install Node.js in an Ubuntu machine.Install Node.js from the Ubuntu repositoryInstall Using a PPA (personal package archive)Using the first method we will not get the latest version of Node.js installed so we will choose the second method where we will get the latest version of Node.js installed.Installing Using a PPA (personal package archive)To get the latest version of Node.js installed on ubuntu, add a PPA (personal package archive). It is maintained by NodeSource.Open terminal and run below commands:Install curl: Run below command on terminalCommand: sudo apt-get install curlSet the NodeSource PPA: Run below command on terminalCommand: curl -sL https://deb.nodesource.com/setup_current.x | sudo -E bash –The PPA will be added to your configuration and your local package cache will be updated automatically.You can read more about available versions of Node.js in nodesource here: https://github.com/nodesource/distributions#debInstall Node.js: Run the below command on terminalCommand: sudo apt-get install -y nodejsCheck for Node.js Installation: Run below command on terminalCommand: node -vIt has to show the version of node installed in this case v15.4.0Now let's see how we can install and setup React app in Ubuntu machineUsing create-react-app (installing create-react-app using npm)Using npx (Recommended in React docs)Using create-react-app (npm)In setting up a React project we come across tools like babel and webpack which are not easy to understand and configure for a person who is new to React and JavaScript. There are several tools that help to sort this problem. One of them is create-react-app. This is the easiest to setup. Create-react-app comes with production grade configurations pre-built. You can alter the configurations by ejecting from the create-react-app as well.Follow the below steps to install using npm create-react-appGo into your desired location where you want to start your react app using ‘cd’ command Run below command to install create-react-app using npm Command: npm install -g create-react-appNow Run create-react-app on terminal to setup a React-app. Command: create-react-app hello-worldThis creates a folder with the name hello-world. You can navigate into the folder using ‘cd’ command and look at the project structure.This gives the React app which we can use, but React recommends using npx.Using npx command:npx is the package runner, since npm version 5.2.0 npx is pre-bundled with npm.Read more about differences npx and npm here: https://www.freecodecamp.org/news/npm-vs-npx-whats-the-difference/Follow the below steps to setup using npx.Go into your desired location where you want to start your react app using ‘cd’ commandRun the below command to setup React app using npxCommand: npx create-react-app my-appThat’s it! Your React app is ready with a single command.This creates a folder with the name hello-world. You can navigate into the folder using ‘cd’ command.  Now open the project in vs-codeWhen you open the project in visual studio code the structure looks like this.Now let's have a look at the files and folders we have:node_modules: This folder is managed by package manager (npm) and contains all the project library dependencies. We should not edit any file inside this folder.public: This folder contains the assets that should be served publicly without any restrictions and contains files like index.html, favicon, manifest.jsonsrc:  This is the folder that contains all the files that are used to create web applications. As a react developer you are likely to spend a lot of time in this folder creating components and other sources of code..gitignore: This file has all the assets which should be ignored by git while we publish our code to GitHub eg: node_modulespackage.json: This is a JSON file which has all information about the app such as name, dependencies, scripts we use to run the application etc.Readme.md: This is a markdown file where you specify the things which you want to show when someone visits your project on GitHub.Now let's run our first React app!Open the terminal integrated with Visual studio code or just stay in the ubuntu terminal; either is fine. Let's use the integrated terminal.Run the app using the following command: Command: npm startThis opens the app in your favourite browser as shown below:Now, let's make our first code changes:On navigating to src folder, you will find App.js file, through which the whole app is run inside the browser. Change the code as you see below and save by hitting ctrl+s.Now look at the browser where the app is running. It looks like the one in the image below.Congratulations on making your first React app!What you have learnt:What is React and why it should be usedWhat is Node.js, and how it should be installed on Ubuntu.What is npmWhat is create-react-appHow to setup React-app on UbuntuHow to run the React-app  How to make code changes to create your first React application.React has rapid changes for every new version. It is important to keep yourself updated with the latest releases of React, so that you can make your life as a React developer easier!
2316
Install And Setup React App on Ubuntu

React is a JavaScript library for building user in... Read More

Understanding the React useReducer Hook

IntroductionThe introduction of Hooks in React brought up a new way of writing and thinking about React applications. One of the most popular Hooks among developers so far is useReducer, which allows us to handle some complex state manipulations and updates, and this is what we’ll be learning about in this article.In React there are two main hooks that are used for state management, and we all know them. These are:useState, anduseReducerYou might have heard or used React.useState hook, and if not you can directly read React’s official documentation about Hooks here.Have you ever found any difficulty in choosing a state management library to manage and handle a global state in a React app? Or, what if you need to manage more complicated data structures or perform any side effects?Thinking over these concepts is quite tricky and time-consuming.Well, this is pretty much what we are going to learn and cover in this article, so read on!  PrerequisitesIn order to get the full benefits of this article, I’d recommend you to double check this prerequisite list and set up the environment as suggested.Npm or Yarn installedNode.js version >= 12.x.x installedcreate-react-app cli installed or use npxBasics of React Hooks, (if not kindly read this first)What is a Reducer, anyway?What is the first thing that comes up in your mind when you hear the term reducer in React?For me, I am always reminded of JavaScript's Array.reducer() function.The only job of a reducer is to Reduce!We all know that the original reduce() method in JavaScript executes a given function for each value of an array  considering from left-to-right. And, here React.useReducer in fact, is like a mini Redux reducer.  A reducer is basically a function which determines a change to an application’s state. It takes the help of an action by using it to receive and determine that particular change.In react we have a lot of options, like Redux, that can help to manage the application’s state changes in a single store. Here we will learn about how we can make use of a reducer to manage shared state in an application.Reducer is one of the new custom Hooks introduced in React since v16.8. It allows you to update parts of your component’s state when certain actions are dispatched, and it is very similar to how Redux works.The reducer in ‘useReducer’ comes from Redux, which in turn borrowed it from JavaScript’s Array.reduce().It carries an initial state and a reducer function as its arguments and then provides a state variable and a dispatch function to enable us to update the state. If you’re familiar with how Redux updates the store through reducers and actions, then you already know how useReducer works. And if not, then also we will learn about useReducer functionality in core.So basically, what is useReducer Hook?The useReducer hook is used for complex state manipulations and state transitions.  Just like the other React hooks, we can import useReducer from react as shown in the below snippet:import React, { useReducer } from 'react';React.useReducer is a React hook function that accepts a reducer function, and an initial state.  const [state, dispatch] = useReducer(reducer, initialState);This hook function returns an array with 2 values. The first one is the state value, and the second value is the dispatch function which is further used to trigger an action with the help of array destructuring.  In the context of React, here’s what a typical useReducer pattern looks like:JSX:const reducer = function (currentState, action) { // Make a new state based on the current state and action return newState}const [state, dispatch] = useReducer(reducer, initialValue)// example usage: dispatch({type: "SOMETHING_HAPPENED"}) // Or with an optional "data": dispatch({type: "SOMETHING_HAPPENED", data: newData})Note: The “state” can be of  any kind. It doesn’t have to be an object always. It could be a number, or an array, or anything else.Pretty cool? Now let’s move further and understand how to use useReducer.How to use the useReducer Hook?Earlier we saw the basic useReducer which takes up two arguments: initial state and a reducer function. But useReducer hook actually takes up one more argument including reducer and initial state which is >>> a function to load the initial state lazily.This is usually helpful when we want the initial state to be different depending on some situation and instead of using our actual state, we could create the initial state anywhere, perhaps dynamically, and it will override the initial state.Syntax for the third argument is:const [state, dispatch] = useReducer(reducer, initialArgs, init); Let’s now understand step by step how to use useReducer and understand what’s happening behind the deck.Consider the following classic example of code to see the practical usage of useReducer:// Let’s begin to define the initial state of the component's state const initialState = { count: 0 } // Here is a function will determine how the state is updated function reducer(state, action) {  switch(action.type) { case 'INCREMENT': return { count: state.count + 1 } case 'DECREMENT': return { count: state.count - 1 } case 'REPLACE': return { count: action.newCount } case 'RESET': return { count: 0 } default: return state } } // Now inside our component, we can initialize the state like below const [state, dispatch] = useReducer(reducer, initialState);Explanation:In the above code snippet , we have  first defined an initial state for our componentadded a reducer function that updates that state depending on the action dispatched and,we have finally initialized the state for our component.Now as promised earlier, you don’t require an understanding of Redux to understand this concept. So let’s break down everything and see what’s happening.The initialState variableThis is the default value of our component’s state when it gets mounted for the first time inside the application.The reducer functionThe next step is to update the component’s state when some actions occur. This function tells what the state should contain depending on the action. It returns an object, which is then used to replace / change the state.It takes in two arguments which are a state and an action; wherein state is nothing but your application’s current state, and the action is an object which contains the details of all the actions currently happening.An action may typically look like this:const replaceAction = { type: 'REPLACE', newCount: 10, }It usually contains a type: which denotes what type of action it is. An action can also contain more than one data, which can also be the new value to be updated in the state.Dispatching an actionNow after understanding about the reducer and how it determines the next state for our component through actions, let’s see how actions are dispatched.Dispatch is just like a function which we can pass around to other components through props.You must have noticed that useReducer returns two values in an array. The first one is the state object, and the second one is a function called dispatch. This is what is used to dispatch an action.For example, if we want to dispatch replaceAction defined in the above example, we’d do something like this:dispatch(replaceAction) // or dispatch({ type: 'REPLACE', newCount: 10, })Summarising a bit here, hence for using useReducer we need the following:Defining an initial stateProviding a function which contains actions that can update the state.Trigger useReducer to dispatch the updated stateUnderstanding useReducer with examplesLet’s play with some real examples now to understand the concept better:Example:1 Simple Classic Counter ExampleLet’s imagine our Component is Counter. useReducer here in the below code accepts as arguments a reducer function, and an initial state value.  const Counter = () => { const [state, dispatch] = useReducer(reducer, 0)}In this case our state is an integer, which starts from 0:The reducer is a function that takes the current state and an action, which can be a value of any type you want. In this example it’s a string:const reducer = (state, action) => { switch (action) { case 'INCREMENT': return state + 1 case 'DECREMENT': return state - 1 default: throw new Error() } }We can use JSX to make this simple component work as below:const Counter = () => {const [count, dispatch] = useReducer(reducer, 0) return ( Counter: {count} dispatch('INCREMENT')}>+ dispatch('DECREMENT')}>- ) } This state can be an object with 'n’ number of properties, but different actions only change one property at a time.Putting up all this together, our Babel will look like:const { useReducer } = React const reducer = (state, action) => { switch (action) { case 'INCREMENT': return state + 1 case 'DECREMENT': return state - 1 default: throw new Error() } } const Counter = () => { const [count, dispatch] = useReducer(reducer, 0) return ( Counter: {count} dispatch('INCREMENT')}>+ dispatch('DECREMENT')}>-  ) } ReactDOM.render(, document.getElementById('app')) You should get the below output:Example2: Let’s see another TODO example. To show list of items:It was not possible to change the state of an item with the handler function earlier. But however, we can now do so, for example if we need to make the list of items stateful we can do so by using them as initial state for our useReducer hook by defining  reducer function:Consider the following JSX snippet for reducer:import React from 'react'; const initialTodo = [...]; const todoReducer = (state, action) => {  switch (action.type) { case 'DO_TODO':      return state.map(todo => { if (todo.id === action.id) { return { ...todo, complete: true }; } else { return todo; } }); case 'UNDO_TODO': return state.map(todo => { if (todo.id === action.id) { return { ...todo, complete: false }; } else { return todo; } }); default: return state; } }; const App = () => { const [todos, dispatch] = React.useReducer( todoReducer, initialTodo ); const handleChange = () => {}; return ( {todos.map(todo => ( ... ))} ); }; export default App; Now we can use the handler to dispatch an action for our reducer function.  Because we need the id as the identifier of a todo item in order to toggle it,  we can pass the item within the handler function by using a encapsulating arrow function as below:const handleChange = todo => { dispatch({ type: 'DO_TODO', id: todo.id }); }; And input will look like: handleChange(todo)} />Let's now implement to check our handler whether a todo item is completed or not by the below condition:const handleChange = todo => { dispatch({ type: todo.complete ? 'UNDO_TODO' : 'DO_TODO', id: todo.id, }); }; Putting up all this together, our component looks like:import React from 'react'; const initialTodo = [ { id: 'a', task: 'Do Something', complete: false,   }, { id: 'b', task: 'Walk over here', complete: false, }, ]; const todoReducer = (state, action) => { switch (action.type) { case 'DO_TODO': return state.map(todo => { if (todo.id === action.id) { return { ...todo, complete: true }; } else { return todo; } }); case 'UNDO_TODO': return state.map(todo => { if (todo.id === action.id) { return { ...todo, complete: false }; } else { return todo; } }); default: return state; } }; const App = () => { const [todos, dispatch] = React.useReducer( todoReducer, initialTodo ); const handleChange = todo => { dispatch({ type: todo.complete ? 'UNDO_TODO' : 'DO_TODO', id: todo.id, }); }; return ( {todos.map(todo => ( handleChange(todo)} /> {todo.task} ))} ); }; export default App; And here is the Output:Now the biggest question is:When do we use React.useReducer instead of React.useState? The answer is very simple and I will try to keep it even more simple:We can Use React.useReducer when -----Your application architecture is complex and big in size  When the logic to update state is super complex or you want to update state deep down in your component treeThe state value is either an object or an arrayYou need a more predictable, and maintainable state architecture of the applicationAnd, we can Use React.useState when -----Your application is smallThe state value is a primitive valueSimple UI state transitionsLogic is not complicated and can stay within one componentConclusionThe useReducer hook is a nice addition to the React library which allows for a  simpler, predictable and organized way to update our component’s state and makes sharing data between components a bit easier.It lets you optimize the performance of the components that trigger deep updates because now you can easily pass dispatch down instead of typical callbacks.And even if you take nothing else from this article, you should at least remember this: that useReducer allows us to define how we update our state value.Happy coding!
3491
Understanding the React useReducer Hook

IntroductionThe introduction of Hooks in React bro... Read More

Install Python on Ubuntu

IntroductionThis article will help you in the installation of python 3  on Ubuntu. You will learn the basics of configuring the environment to get started with Python.Brief introduction to PythonPython is an Interpreted programming language that is very popular these days due to its easy learning curve and simple syntax. Python finds use in many applications and for programming the backend code of websites. It is also very popular for data analysis across industries ranging from medical/scientific research purposes to retail, finances, entertainment, media and so on.When writing a python program or program in any other language, people usually use something called an IDE or Integrated Development Environment that includes everything you need to write a program. It has an inbuilt text editor to write the program and a debugger to debug the programs as well.Latest version of pythonThe latest version of python is python3 and the latest release is python3.9.0.Installation linksFor downloading python and the documentation for Ubuntu, visit the official website https://www.python.org/downloads/ and go to the downloads section, from where you can download the latest python version for Ubuntu.Key terms (pip, virtual environment, path etc.)       pip:pip is a package manager to simplify installation of python packages. To install pip ,run the below command on the terminalsudo apt  install  python3-pip  Once the installation is done just install a package  by runningpip install virtual environment:The purpose of virtual environments is to have a separate space where you can install packages which are specific to a certain project, For example if you have lot of flask or Django- based applications and not all the applications are using the same version, we use virtual env where each project will have its own version.In order to use a virtual environment you need to be on the python 3.x version. Let’s understand how to create the virtual environment. You do not need any library as it comes along with standard python installation.If you don't have virtual environment installed, use this command to install it:pip3 install virtualenvSo to create a new virtual env, run the below command:virtualenv env (name of virtual env)This will create a virtual environment and will install some standard packages as well as part of the virtual environment creation.To activate the virtual environment on ubuntu, use the below command:source env/bin/activateTo deactivate it you can run the below command in the environment:deactivateGetting and Installing Ubuntu:To download Python, visit the official website https://www.python.org/downloads/ and go to the downloads section. You can download the latest python version for Ubuntu as shown below:Download the tarball and untar the file. After untarring the file, you will see a couple of files. The file you will be interested in is readme file where you can access a set of instructions to install the python on the ubuntu machine.Open the terminal, change the directory of the untarred python file, and run the below command under cd ~/Install python command:./configuremakemake testsudo make installThis will install python as python3.If you get an error when running sudo ./configure, like no compiler found, just install the below library to get rid of it:apt-get install build-essentialAlso if you get an error when running, like make not found, just run the below command to install make:sudo apt install makeSo once you are done installing the above libraries, like make and build-essential, you should be good with the above install python command.The other way of installing python is by running apt get commands as below:Open the terminal and run:sudo apt-get updateThis will make sure repos are updated to the latest in Ubuntu. Install python by running the below command:sudo apt-get install python3Setting pathTo find the existing  system path set in your machine, you can run the below command:echo  $PATHNow suppose you want to set a different path for your Python executable, you can just use export command and give it a directory path like below:export PATH=$PATH:`’By just running the above export command, this will not be persisted across different terminals. Again, if you close that terminal and open it again, the change would have been lost. So to make it persistent,  you need to add the above command in the ~/.bashrc file present in the home directory of the ubuntu system.How to run python codeTo run python code just run the commandpython Installing Additional Python Packages:If you want to see what all packages are installed in the env, run the command pip3 list which will list down the current packages installed in the env. If you install any other packages in the env, for instance let’s say you want to install request library, you can just install it by running pip3 install requests. Now try running pip3 list again to see this requests lib installed in this env.Directory as package for distribution:Inside the python project or directory you should have a file called __init__.py inside the directory. So you can create this file by a simple touch command. This file does not need to have any data inside it, it only has to exist inside the directory for that to work as a package.Documentation links for pythonhttps://www.python.org/doc/Conclusion (Summary)This article will help you with stepwise instructions on the installation of Python on ubuntuOs.
3477
Install Python on Ubuntu

IntroductionThis article will help you in the inst... Read More

How to Install Python on Mac

1. IntroductionThis article will help you in the installation of Python 3  on macOS. You will learn the basics of configuring the environment to get started with Python.2. Brief introduction to PythonPython is an Interpreted programming language that is very popular these days due to its easy learning curve and simple syntax. Python finds use in many applications and for programming the backend code of websites. It is also very popular for data analysis across industries ranging from medical/scientific research purposes to retail, finances, entertainment, media and so on.When writing a python program or program in any other language, people usually use something called an IDE or Integrated Development Environment that includes everything you need to write a program. It has an inbuilt text editor to write the program and a debugger to debug the programs as well. PyCharm is a well-known IDE for writing python programs.3. Latest version of pythonThe latest version of python is python3 and the latest release is python3.9.0.4. Installation linksFor downloading python and the documentation for MacOS, visit the official website https://www.python.org and go to the downloads section, from where you can download the latest python version for MacOS.5. Key terms (pip, virtual environment, path etc.)pip:pip is a package manager to simplify the installation of python packages. To install pip, run the below command on the terminal:curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py.If you install python by using brew which is a package management to simplify installation of software on macOs, it installs other dependent  packages as well along with python3  like pip etc.virtual environment:The purpose of virtual environments is to have a separate space where you can install packages which are specific to a certain project. For example if you have a lot of flask or Django-based applications and not all the applications are using the same version, we use virtual env wherein each project will have its own version.In order to use a virtual environment you need to be on the python 3.x version. Let’s understand how to create the virtual environment. You do not need any library as it comes along with standard python installation.So to create a new virtual env, run the below command:python3 -m venv demo-m expects a module name which is venv in this case, so with this python searches your sys.path and executes the module as the main module.Venv expects an environment name that you must create.Now you should have a new environment called demo. Let’s activate this virtual env by running the below command:source demo/bin/activateAfter running this, the environment is activated and you can see the environment name in the terminal. Another way to check if the env is activated is by running which python. You will see the python that you are using with this project env, and the version that it will use is the same that you used to create the environment.6. Getting and Installing MacPython:For MacOS, python usually comes pre-installed, so to check if python is installed open the terminal in the mac and use `python --version` to confirm the same. You can also see what is the default python version installed, which is usually python2.x by default. However, Python2.x is going to get deprecated soon, and with everyone moving to python3.x ,we will go with the latest python3 installation.7. Installation stepsFor downloading python, visit the official website https://www.python.org and go to the downloads section. You can download the latest python version for MacOS as shown below:It will download a pkg file. Click on that file to start the installation wizard. You can continue with default settings. If you want to change the install location, however,  you can change it, and then continue and finish the installation with the rest of the default settings.Once the installation is finished it would have created the python 3.x directory in the application folder. Just open the application folder and verify the same.Now you have python3.x installed.To verify it from the terminal, go to the terminal and check the version of python by using `python --version` command. So you will still see it is showing the old default python version, Now instead if you use python3 explicitly like `python3 –version, you can see the version that you have installed with python3 version.Once the installation is finished it would have created a python3.x directory in the application folder. Open the application folder and verify the same.You can also install python3 on mac by using brew which is a package management to simplify installation of software on macOs.brew install python3brew will install other dependent  packages as well along with python3  like pip etc8. Setting pathSuppose you have installed a new python 3  version but when you type python it still shows the default python2 version which comes by default in mac os. To solve this, add an alias by runningalias python=python3Add this line in the file called .bash_profile present in home directory. In case this file is not present, you can create it, save the changes and restart the terminal by closing it. Next, open the terminal and run python and hit enter. You should see the latest python3 that you have installed.Sometimes when you type python or python3 explicitly, it does not work even if you have installed the python. You get the message, “command is not found”. This means the command is not present in the directories used by the machine for lookup. Let’s  check the directories where the machine is looking for commands by runningecho $PATHIt will list all your directories where the machine looks for commands. This will vary from machine to machine. If the command that you are trying is not under the directory path listed by echo, that command will not work. It will throw an error saying command is not present, until you provide the full path of the directory where it's installed.Now let’s open the file  .bash_profile and add the directory path where python is installed to the current path env variableFor example  let’s add the following lines in that bash_profile file which will add the below directory to the current env variable. This can vary from machine to machine based on the installed location.PATH=”/Library/Frameworks/Python.framework/Versions/3.7/bin:${PATH}”export PATHSave the changes and restart the terminal. Open the terminal now and run echo $PATH again and see the above path that you added for python3. When you now type python3 command, you should see it working.  Also, if you are trying to import a package that you have installed and it says that it cannot find that package, this means pip install is installing the packages in the different version of python directory. Make sure the location of the package is in the site-packages directory of the version of the python that you are using. You can see the location of the package that you are trying to import by running  pip show The above command will have a location field in which you can see and cross verify the path.9. How to run python codeTo run python code just run the commandpython 10. Installing Additional Python Packages:If you want to see what all packages are installed in the env, run the command pip3 list which will list down the current packages installed. Let’s say you want to install request library. You can just install it by running pip3 install requests. Now try running pip3 list again, to see this requests lib installed in this env.11. Directory as package for distribution:Inside the python project or directory you should have a file called __init__.py. You can create this file by a simple touch command, and this file does not need to have any data inside it, All it has to do is to exist inside the directory, for that to work as a package.12. Documentation links for pythonhttps://www.python.org/doc/13. Conclusion (Summary)This article will help you with stepwise instructions on the installation of python on mac.
4445
How to Install Python on Mac

1. IntroductionThis article will help you in the i... Read More

Essential Steps to Mastering Machine Learning with Python

One of the world’s most popular programming languages today, Python is a great tool for Machine Learning (ML) and Artificial Intelligence (AI). It is an open-source, reusable, general-purpose, object-oriented, and interpreted programming tool. Python’s key design ideology is code readability, ease of use and high productivity. The latest trend shows that the interest in Python has grown significantly over the past five years. Python is the top choice for ML/AI enthusiasts when compared to other programming languages.   Image source: Google Trends - comparing Python with other tools in the marketWhat makes Python a perfect recipe for Machine Learning? Python can be used to write Machine Learning algorithms and it computes pretty accurately. Python’s concise and easy readability allows the writing of reliable code very quickly. Another reason for its popularity is the availability of various versatile, ready-to-use libraries.  It has an excellent library ecosystem and a great tool for developing prototypes. Unlike R, Python is a general-purpose programming language which can be used to build web applications and enterprise applications.  The community of Python has developed libraries that adhere to a particular area of data science application. For instance, there are libraries available for handling arrays, performing numerical computation with matrices, statistical computing, machine learning, data visualization and many more. These libraries are highly efficient and make the coding much easier with fewer lines of codes. Let us have a brief look at some of the important Python libraries that are used for developing machine learning models. NumPy: One of the fundamental packages for numerical and scientific computing. It is a mathematical library to work with n-dimensional arrays in Python. Pandas: Provides highly efficient, easy-to-use DataFrame for DataFrame manipulations and Exploratory Data Analysis (EDA). SciPy: SciPy is a functional library for scientific and high-performance computations. It contains modules for optimization and for several statistical distributions and tests. Matplotlib: It is a complete plotting package that provides 2D plotting as well as 3D plotting. It can plot static and interactive plots. Seaborn: Seaborn library is based on Matplotlib. It is used to plot more elegant statistical visualization.  StatsModels: The StatsModels library provides functionalities for estimation of various statistical models and conducting different statistical tests. Scikit-learn: Scikit-Learn is built on NumPy, SciPy and Matplotlib. Free to use, overpowered and provides various range of supervised and unsupervised machine learning algorithms. One should also take into account the importance of IDEs specially designed for Python for Machine Learning. The Jupyter Notebook  -  an open-source web-based application that enables ML enthusiasts to create, share, quote, visualize, and live-code their projects.  There are various other IDEs that can be used like PyCharm, Spyder, Vim, Visual Studio Code. For beginners, there is a nice simple online compiler available – Programiz. Roadmap to master Machine Learning Using Python Learn Python: Learn Python from basic to advanced. Practice those features that are important for data analysis, statistical analysis and Machine Learning. Start from declaring variables, conditional statements, control flow statements, functions, collection objects, modules and packages. Deep dive into various libraries that are used for statistical analysis and building machine learning models. Descriptive Analytics : Learn the concept of descriptive analytics, understand the data, learn to load structured data and perform Exploratory Data Analysis (EDA). Practice data filtering, ordering, grouping, multiple joining of datasets. Handle missing values, prepare visualization plots in 2D or 3D format (from libraries like seaborn, matplotlib) to find hidden information and insights. Take a break from Python and Learn Stats - Learn the concept of the random variable and its important role in the field of analytics. Learn to draw insights from the measures of dispersion (mean, median, mode, quartiles and other statistical measures like confidence interval and distribution functions. The next step is to understand probability & various probability distributions and their crucial role in analytics. Understand the concept of various hypothesis tests like t-tests, z-test, ANOVA (Analysis of Variance), ANCOVA (Analysis of Covariance), MANOVA (Multivariate Analysis of Variance), MANCOVA (Multivariate Analysis of Covariance) and chi-square test.  Understand Major Machine Learning AlgorithmsImage sourceDifferent algorithms have different tasks. It is advisable to understand the context and select the right algorithm for the right task. Types of ML ProblemDescriptionExamplesClassificationPick one of N labelsPredict if loan is going to be defaulted or notRegressionPredict numerical valuesPredict property priceClusteringGroup similar examplesMost relevant documentsAssociation rule learningInfer likely association patterns in dataIf you buy butter you are likely to buy bread (unsupervisedStructured OutputCreate complex outputNatural language parse trees, images recognition bounding boxesRankingIdentify position on a scale or statusSearch result rankingSourceA. Regression (Prediction):  Regression algorithms are used for predicting numeric values. For example, predicting property price, vehicle mileage, stock prices and so on.   SourceB. Linear Regression – predicting a response variable, which is numeric in nature, using one or more features or variables. Linear regression model is mathematically represented as:  SourceVarious regression algorithms include: Linear Regression Polynomial Regression  Exponential Regression Decision Tree Random Forest Neural Network As a note to new learners, it is suggested to understand the concepts of – Regression assumptions, Ordinary Least Square Method, Dummy Variables (n-1 dummy encoding, one hot encoding), and performance evaluation metrics (RMSE, MSE, MAD). Classification - We use classification algorithms for predicting a set of items’ classes or a categorical feature. For example, predicting loan default (yes/no) or predicting cancer (yes/no) and so on. Various classification algorithms include: Binomial Logistic Regression Fractional Binomial Regression Quasibinomial Logistic regression Decision Tree Random Forest Neural Networks K-Nearest Neighbor Support Vector Machines Some of the classification algorithms are explained here: K-Nearest Neighbors – simple yet often used classification algorithm. It is a non-parametric algorithm (does not make any assumption on the underlying data distribution) It chooses to memorize the learning instances The output is a class membership  There are three key elements in this approach – a set of labelled objects, eg, a set of stored records, a distance between objects, and the value of k, the number of nearest neighbours  Distance measures that the K-NN algorithm uses - Euclidean distance (square root of the sum of the squared distance between a new point and the existing point across all the input attributes.  Other distances include – Hamming distance, Manhattan distance, Minkowski distance  SourceExample of K-NN classification. The test sample (green dot) should be classified either to blue squares or to red triangles. If k = 3 (solid line circle) it is assigned to the red triangles because there are 2 triangles and only 1 square inside the inner circle. In other words the number of triangles is more than the number of squares If k = 5 (dashed line circle) it is assigned to the blue squares (3 squares vs. 2 triangles inside the outer circle). It is to be noted that to avoid equal voting, the value of k should be odd and not even.  Logistic Regression – A supervised algorithm that is used for binary classification. The basis for logistic regression is the logit feature aka sigmoid characteristic which takes any real value and maps it between zero and 1. In other words, Logistic Regression returns a probability value for the class label.   SourceIf the output of the sigmoid function is more than 0.5, we can classify the outcome as 1 or YES, and if it is less than 0.5, we can classify it as 0 or NO For instance, let us take cancer prediction. If the output of the Logistic Regression is 0.75, we can say in terms of probability that, “There is a 75 percent chance that the patient will suffer from cancer.” Decision Tree – Is a type of supervised learning algorithm which is most commonly used in the case of a classification problem. Decision Tree algorithms can also be used for regression problems i.e. to predict a numerical response variable. In other words, Decision Tree works for both categorical and continuous input and output variables. Each branch node of the decision tree represents a choice between some alternatives and each leaf node represents a decision. SourceAs an early learner, it is suggested to understand the concept of ID3 algorithm, Gini Index, Entropy, Information Gain, Standard Deviation and Standard Deviation Reduction. Random Forest – is a collection of multiple decision trees. It is a supervised learning algorithm, that can be used for both classification & regression problems. While algorithms like Decision Tree can cause a problem of overfitting wherein a model performs well in training data but does not perform well in testing or unseen data, algorithms like Random Forest can help avoid overfitting. It achieves uncorrelated decision trees throughout the concept of bootstrapping (i.e. sampling with replacement) and features randomness.  SourceAs a new learner it is important to understand the concept of bootstrapping.  Support Vector Machine – a supervised learning algorithm, used for classification problems. Another flavour of Support Vector Machines (SVM) is Support Vector Regressor (SVR) which can be used for regression problems. In this, we plot each data item as a point in n-dimensional space n here represents the number of features SourceThe value of each feature is the value of a particular coordinate.  Classification is performed by finding hyperplanes that differentiate the two classes.  It is important to understand the concept of margin, support vectors, hyperplanes and tuning hyper-parameters (kernel, regularization, gamma, margin). Also get to know various types of kernels like linear kernel, radial basis function kernel and polynomial kernel Naive Bayes – a supervised learning classifier which assumes features are independent and there is no correlation between them. The idea behind Naïve Bayes algorithm is the Bayes theorem.  SourceC.Clustering Clustering algorithms are unsupervised algorithms that are used for dividing data points into groups such that the data points in each group are similar to each other and very different from other groups.  Some of the clustering algorithms include: K-means – An unsupervised learning algorithm in which the items are grouped into k-cluster The elements of the cluster are similar or homogenous. Euclidean distance is used to calculate the distance between two data points. Data points have a centroid; this centroid represents the cluster. The objective is to minimize the intra-cluster variations or the squared error function.SourceOther types of clustering algorithms: DBSCAN Mean Shift Hierarchical d) Association Association algorithms, which form part of unsupervised learning algorithms, are for associating co-occurring items or events. Association algorithms are rule-based methods for finding out interesting relationships in large sets of data. For example, find out a relationship between products that are being bought together – say, people who buy butter also buy bread. Some of the association algorithms are: Apriori Rules - Most popular algorithm for mining strong associations between variables. To understand how this algorithm works, concepts like Support, Confidence & Lift to be studied. ECLAT - Equivalence Class Clustering and bottom-up Lattice Traversal. This is one of the popular algorithms that is used for association problems. This algorithm is an enhanced version of the Apriori algorithm and is more efficient. FP Growth - Frequent Pattern Growth Algorithm - Another very efficient & scalable algorithm for mining associations between variables e) Anomaly Detection We recommend the use of anomaly detection for discovering abnormal activities and unusual cases like fraud detection. An algorithm that can be used for anomaly detection: Isolation Forest - This is an unsupervised algorithm that can help isolate anomalies from huge volume of data thereby enabling anomaly detection f) Sequence Pattern Mining We use sequential pattern mining for predicting the next data events between data examples in a sequence. Predicting the next dose of medicine for a patient g) Dimensionality ReductionDimensionality reduction is used for reducing the dimension of the original data. The idea is to reduce the set of random features by obtaining a set of principal components or features. The key thing to understand in this is that the components retain or represent some meaningful properties of the original data. It can be divided into feature extraction and selection. Algorithms that can be used for dimensionality reduction are: SourcePrincipal Component Analysis - This is a dimensionality reduction algorithm that is used to reduce the number of dimensions or variables in large datasets that have a very high number of variables. However it is to be noted that though PCA transforms a very large set of features or variables into smaller sets, it helps retain most of the information of the dataset. While the reduction of dimensions comes at a cost of model accuracy, the idea is to bring in simplicity in the model by reducing the number of variables or dimensions.  h) Recommendation Systems - Recommender Systems are used to build recommendation engines. Recommender algorithms are used in various business areas that include online stores to recommend the right product to its buyers like Amazon , content recommendation for online video & music sites like Netflix, Amazon Prime Music and various social media platforms like FaceBook, Twitter and so on.   SourceRecommender Engines can be broadly categorized into the following types: Content-based methods — recommends items to a user based on their profile history. It revolves around customer’s taste and preference.  Collaborating filtering method — it can be further subdivided into two categories Model-based — a stipulation wherein user and item interact. Both user and item interaction are learned from interactions matrix. Memory-based — Unlike model-based it relies on the similarity between the users and the items. Hybrid methods — Mix content which is based on collaborative filtering approaches. Examples: Movie recommendation system Food recommendation system E-commerce recommendation system 5. Choose the Algorithm — Several machine learning models can be used with the given context. These models are chosen depending on the data (image, numerical values, texts, sounds) and the data distribution 6. Train the model — Training the model is a process in which the machine learns from the historical data and provides a mathematical model that can be used for prediction. Different algorithms use different computation methods to compute the weights for each of the variables. Some algorithms like Neural Network initialize the weight of the variables at random. These weights are the values which affect the relationship between the actual and the predicted values.  7. Evaluation metrics to evaluate the model— Evaluation process comprises understanding the output model and evaluating the model accuracy for the result. There are various metrics to evaluate model performance. Regression problems have various metrics like MSE, RMSE, MAD, MAPE as key evaluation metrics while classification problems have metrics like Confusion Matrix, Accuracy, Sensitivity (True Positive Rate), Specificity (True Negative Rate), AUC (Area under ROC Curve), Kappa Value and so on. It is only after the evaluation, the model can be improved or fine-tuned to get more accurate predictions. It is important to know a few more concepts like:  True Positive  True Negative  False Positive  False Negative  Confusion Matrix  Recall (R) F1 Score ROC AUC Log loss When we talk about regression the most commonly used regression metrics are: Mean Absolute Error (MAE) Mean Squared Error (MSE) Root Mean Squared Error (RMSE) Root Mean Squared Logarithmic Error (RMSLE) Mean Percentage Error (MPE) Mean Absolute Percentage Error (MAPE) We must know when to use which metric. It depends on the kind of data and the target variable you have. 8. Tweaking the model or the hyperparameter tuning  - With great models, comes the great problem of optimizing hyperparameters to build an improved and accurate ML model. Tuning certain parameters (which are called hyperparameters) is important to ensure improved performance. The hyperparameters vary from algorithm to algorithm and it is important to learn the hyperparameters for each algorithm.  9. Making predictions  - The final nail to the coffin. With all these aforementioned steps followed one can tackle real-life problems with advanced Machine Learning models.  Steps to remember while building the ML model: Data assembling or data collection  - generally represents the data in the form of the dataset.  Data preparation - understanding the problem statement. This includes data wrangling for building or training models, data cleaning, removing duplicates, checking for missing values, data visualization for understanding the relationship between variables, checking for (imbalanced) bias data, and other exploratory data analysis. It also includes splitting the data into train and test. Choosing the model  -  the ML model which answers the problem statement. Different algorithms serve different purposes. Training the model  -  the idea to train the model is to ensure that the prediction is accurate more often. Model evaluation — evaluation metric to measure the performance of the model. How does the model perform against the previously unseen data? The train/test splitting ratio — (70:30) or (80:20), depending on the dataset. There is no exact rule to split the data by (80:20) or (70:30); it depends on the data and the target variable. Some of the data scientists use a range of 60% to 80% for training and the rest for testing the model. Parameter tuning  - to ensure improved performance by controlling the model’s learning process. The hyperparameters have to be tuned so that the model can optimally solve the machine learning problem. For parameter tuning, we either specify a grid of parameters known as the grid search or we randomly select a combination of parameters known as the random search.GridSearchCV — It is the process to search the best combination of parameters over the grid. For instance, n_estimator could possibly be 100,250,350,500; max_depth can be 2,5,11,15 and the criterion could be gini or entropy. Though these don’t look like a lot of parameters, just imagine the scenario if the dataset is too large. The grid search has to run on a loop and calculate the score on the validation set. RandomSearchCV —We randomly select a combination of parameters and then calculate the cross-validation score. It computes faster than GridSearch. Note: Cross-validation is the first and most essential step when it comes to building ML models. If the cross-validation score is good, we can say that the validation data is a representation of training or the real-world data. Finally, making predictions — using the test data, of how the model will perform in real-world cases. ConclusionPython has an extensive catalogue of modules and frameworks. It is fast, less complex and thus it saves development time and cost. It makes the program completely readable particularly for novice users. This particular feature makes Python an ideal recipe for Machine Learning.  Both Machine Learning and Deep Learning require work on complex algorithms and several workflows. When using Python, the developer can worry less about the coding, and can focus more on finding the solution. It is open-source and has an abundance of available resources and step-by-step documentation. It also has an active community of developers who are open to knowledge sharing and networking. The benefits and the ease of coding makes Python the go to choice for developers. We saw how Python has an edge over other programming tools, and why knowledge of Python is essential for ML right now.  Summing up we saw the benefits of Python, the way ahead for beginners and finally the steps required in a machine learning project. This article can be considered as a roadmap to your mastery over Machine Learning. 
6627
Essential Steps to Mastering Machine Learning with...

One of the world’s most popular programming lang... Read More