Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Applied Supervised Learning with R
Applied Supervised Learning with R

Applied Supervised Learning with R: Use machine learning libraries of R to build models that solve business problems and predict future trends

Arrow left icon
Profile Icon Karthik Ramasubramanian Profile Icon Jojo Moolayil
Arrow right icon
$19.99 per month
Paperback May 2019 502 pages 1st Edition
eBook
$24.99 $35.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Karthik Ramasubramanian Profile Icon Jojo Moolayil
Arrow right icon
$19.99 per month
Paperback May 2019 502 pages 1st Edition
eBook
$24.99 $35.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$24.99 $35.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Applied Supervised Learning with R

Chapter 2. Exploratory Analysis of Data

Note

Learning Objectives

By the end of this chapter, you will be able to:

  • Define a problem statement with industry standard frameworks

  • Perform univariate and bivariate analysis

  • Explain multivariate analysis

  • Perform hypothesis testing

  • Perform data wrangling using the dplyr and reshape2 packages

  • Visualize data using the ggplot2 package

Note

In this chapter, we will acquaint learners with techniques to clean, transform, and visualize data in order to get useful insights.

Introduction


Chapter 1, R for Advanced Analytics, introduced to you the R language and its ecosystem for data science. We are now ready to enter a crucial part of data science and machine learning, that is, Exploratory Data Analysis (EDA), the art of understanding the data.

In this chapter, we will approach EDA with the same banking dataset used in the previous chapter, but in a more problem-centric way. We will start by defining the problem statement with industry standard artifacts, design a solution for the problem, and learn how EDA fits in the larger problem framework. We will then tackle the EDA for the direct marketing campaigns (phone calls) of a Portuguese banking institution use case using a combination of data engineering, data wrangling, and data visualization techniques in R, backed up by a business-centric approach.

In any data science use case, understanding the data consumes the bulk of the time and effort. Most data science professionals spend around 80% of their time understanding...

Defining the Problem Statement


If you recollect the data we explored in Chapter 1, R for Advanced Analytics, bank marketing data, we have a dataset that captures the telemarketing campaigns conducted by a bank to attract customers.

A large multinational bank is designing a marketing campaign to achieve its growth target by enticing customers for bank deposits. The campaign has been ineffective in luring customers, and the marketing team wants to understand how the campaign can be improved to achieve the growth targets.

We can reframe the problem from the business stakeholders' perspective and try to see what kind of solution would best fit here.

Problem-Designing Artifacts

Just like there are several frameworks, templates, and artifacts for software engineering and other industrial projects, data science and business analytics projects can also be effectively represented using industry standard artifacts. Some popular choices are available from consulting giants such as McKinsey, BCG, and decision...

Understanding the Science Behind EDA


In layman's terms, we can define EDA as the science of understanding data. A more formal definition is the process of analyzing and exploring datasets to summarize its characteristics, properties, and latent relationships using statistical, visual, analytical, or a combination of techniques.

To cement our understanding, let's break down the definition further. The dataset is a combination of numeric and categorical features. To study the data, we might need to explore features individually, and to study relationships, we might need to explore features together. Depending on the number of features and the type of features, we may cross paths with different types of EDA.

To simplify, we can broadly classify the process of EDA as follows:

  • Univariate analysis: Studying a single feature

  • Bivariate analysis: Studying the relationship between two features

  • Multivariate analysis: Studying the relationship between more than two features

For now, we will restrict the scope...

Exploratory Data Analysis


We will get started with the dataset available to download from UCI ML Repository at https://archive.ics.uci.edu/ml/datasets/Bank%20Marketing.

Download the ZIP file and extract it to a folder in your workspace and use the file named bank-additional-full.csv. Ask the students to start a new Jupyter notebook or an IDE of their choice and load the data into memory.

Exercise 18: Studying the Data Dimensions

Let's quickly ingest the data using the simple commands we explored in the previous chapter and take a look at a few essential characteristics of the dataset.

We are exploring the length and breadth of the data, that is, the number of rows and columns, the names of each column, the data type of each column, and a high-level view of what is stored in each column.

Perform the following steps to explore the bank dataset:

  1. First, import all the required libraries in RStudio:

    library(dplyr)
    library(ggplot2)
    library(repr)
    library(cowplot)
  2. Now, use the option method to set the width...

Univariate Analysis


Univariate analysis is the study of a single feature/variable. Here, we describe the data to help us get an overall view of how it is organized. For numeric features, such as age, duration, nr.employed (numeric features in the dataset) and many others, we look at summary statistics such as min, max, mean, standard deviation, and percentile distribution. These measures together help us understand the spread of the data. Similarly, for categorical features such as job, marital, and education, we need to study the distinct values in the feature and the frequency of these values. To accomplish this, we can implement a few analytical, visual, and statistical techniques. Let's take a look at the analytical and visual techniques for exploring numeric features.

Exploring Numeric/Continuous Features

If you explored the previous output snippet, you might have noted that we have a mix of numeric and categorical features in the dataset. Let's start by looking at the first feature in...

Exploring Categorical Features


Categorical features differ from numeric or continuous features in nature, and therefore the traditional methods used earlier aren't applicable here. We can analyze the number of different classes within a categorical variable and the frequency associated with each. This can be achieved using either simple analytical techniques or visual techniques. Let's explore a list of categorical features using a combination of both.

Exercise 24: Exploring Categorical Features

In this exercise, we will start with a simple variable, that is, marital, which indicates the marital status of the client. Let's use the dplyr library to perform grouped data aggregation.

Perform the following steps to complete the exercise:

  1. First, import the dplyr library in the system using the following command:

    library(dplyr)
  2. Next, we will create an object named marital_distribution and store the value based on the following condition:

    marital_distribution <- df %>% group_by(marital) %>% ...

Bivariate Analysis


In bivariate analysis, we extend our analysis to study two variables together. In our use case, we have around 20 independent variables. It is indeed possible to study all permutation combinations of the available 20 variables, but we won't go to that extent in this chapter. In our use case, we are more interested in studying all the factors that led to the poor performance of the campaign. Therefore, our primary focus will be to perform bivariate analysis and study the relationship between all the independent variables and our dependent target variable. Again, depending on the type of variable, we will have a different type of visual or analytical technique to analyze the relationship between the two variables. The possible combinations are numeric and numeric, and numeric and categorical. Given that our dependent variable is a categorical variable, we might have to explore the relationship between two independent variables in our list to study the relationship between...

Studying the Relationship between Two Numeric Variables


To understand how we can study the relationship between two numeric variables, we can leverage scatter plots. It is a 2-dimensional visualization of the data, where each variable is plotted on an axis along its length. Relationships between the variables are easily identified by studying the trend across the visualization. Let's take a look at an example in the following exercise.

Exercise 30: Studying the Relationship between Employee Variance Rate and Number of Employees

Let's study the relationship between employee variance rate and the number of employees. Ideally, the number of employees should increase as the variation rate increases.

Perform the following steps to complete the exercise:

  1. First, import the ggplot2 package using the following command:

    library(ggplot2)
  2. Create a DataFrame object, df, and use the bank-additional-full.csv file using the following command:

    df <- read.csv("/Chapter 2/Data/bank-additional/bank-additional-full...

Studying the Relationship between a Categorical and a Numeric Variable


Let's first recall the methods discussed to study the relationship between the numeric and categorical variable and discuss the approach to execute it.

In this section, we will discuss the different aggregation metrics that we can use for summarizing the data. So far, we have used avg, but a better approach would be to use a combination of avg, min, max, and other metrics.

Exercise 31: Studying the Relationship between the y and age Variables

We have a categorical dependent variable and nine numeric variables to explore. To start small, we will first explore the relationship between our target, y, and age. To study the relationship between a categorical and numeric variable, we can choose a simple analytical technique where we calculate the average age across each target outcome; if we see stark differences, we can make insights from the observations.

In this exercise, we will calculate the average age across each target...

Studying the Relationship Between Two Categorical Variables


To study the relationship and patterns that exist between two categorical variables, we can first explore the frequency distribution across each category of the variables. A higher concentration in any outcome might be a potential insight. The most effective way to visualize this is using stacked bar charts.

A stacked bar chart will help us to observe the distribution of the target variable across multiple categorical variables. The distribution will reveal whether a specific category in a categorical variable dominates the target variable, y. If yes, we can further explore its influence on our problem.

In the next few exercises, we will explore various categorical variables across target variable y using stacked bar chart. We will plot absolute count and percentage to understand the distribution better.

Exercise 34: Studying the Relationship Between the Target y and marital status Variables

In this exercise, we will demonstrate the...

Multivariate Analysis


Multivariate analysis is the process of studying the relationships between more than two variables; essentially, one dependent variable and more than one independent variable. Bivariate analysis is a form of multivariate analysis. There are several forms of multivariate analysis that are important, but we will skip the details for now to restrict the scope of the chapter. In the next few chapters, we will take a closer look at linear and logistic regression, which are two popular multivariate analysis techniques.

Some of the most common techniques used in multivariate analysis are as follows:

  • Multiple linear regression (studying the impact of more than one independent variable on a numeric/continuous target variable)

  • Logistic regression (studying the impact of more than one independent variable on a categorical target variable)

  • Factor analysis

  • MANOVA

Validating Insights Using Statistical Tests


Throughout the journey of EDA, we have collected and noted some interesting patterns for further validation. It is now the right time to test whether whatever we observed previously are actually valid patterns or just appeared to be interesting due to random chance. The most effective and straightforward way to approach this validation is by performing a set of statistical tests and measuring the statistical significance of the pattern. We have a ton of options in the available set of tests to choose from. The options vary based on the type of independent and dependent variable. The following is a handy reference diagram that explains the types of statistical test that we can perform to validate our observed patterns:

Figure 2.24: Validating dependent and independent variables

Let's collect all our interesting patterns into one place here:

  • The campaign outcome has a higher chance of yes when the employee variance rate is low.

  • The campaign outcome has...

Categorical Dependent and Numeric/Continuous Independent Variables


Hypotheses 1 and 2 have a continuous independent variable. Referring to the figure in the previous section, we will opt for the chi-squared test. In the process of hypothesis testing, we start by defining a null hypothesis and an alternate hypothesis. Start with a negative approach, that is, assume the null hypothesis to be what we don't want to happen. The hypothesis test examines the chances that the pattern observed happens due to random chance or there if is certainty about the observation. This measure is quantified as probability. If the probability of the significance of the null hypothesis to happen is less than 5% (or a suitable cut-off), we reject the null hypothesis and confirm the validity of the alternate hypothesis.

Let's begin; for hypothesis 1, we define the following:

  • Null hypothesis: The campaign outcome has no relationship with the employee variance rate.

  • Alternate hypothesis: The campaign outcome has a relationship...

Categorical Dependent and Categorical Independent Variables


Moving on, let's take a look at the third hypothesis. To test the relationship between the categorical dependent variable and categorical independent variable, we can use the chi squared test.

For hypothesis 3, we define the following:

  • Null hypothesis: The campaign outcome has no relationship with clients who never married.

  • Alternate hypothesis: The campaign outcome has a relationship with clients who never married.

In the following exercise, we will leverage R's chi-square test function to validate the hypothesis..

Exercise 38: Hypothesis 3 Testing for Categorical Dependent Variables and Categorical Independent Variables

In this exercise, we will perform a statistical test using the chi-squared test. We use the chi-squared test because both the independent and dependent variables are categorical, particularly when testing the relationship between y and marital status.

Perform the following steps:

  1. Import the required libraries and create...

Summary


In this chapter, we explored EDA using a practical use case and traversed the business problem. We started by understanding the overall process of executing a data science problem and then defined our business problem using an industry standard framework. With the use case being cemented with appropriate questions and complications, we understood the role of EDA in designing the solution for the problem. Exploring the journey of EDA, we studied univariate, bivariate, and multivariate analysis. We performed the analysis using a combination of analytical as well as visual techniques. Through this, we explored the R packages for visualization, that is, ggplot and some packages for data wrangling through dplyr. We also validated our insights with statistical tests and, finally, collated the insights noted to loop back with the original problem statement.

In the next chapter, we will lay the foundation for various machine learning algorithms, and discuss supervised learning in depth.

Left arrow icon Right arrow icon

Key benefits

  • Study supervised learning algorithms by using real-world datasets
  • Fine-tune optimal parameters with hyperparameter optimization
  • Select the best algorithm using the model evaluation framework

Description

R provides excellent visualization features that are essential for exploring data before using it in automated learning. Applied Supervised Learning with R helps you cover the complete process of employing R to develop applications using supervised machine learning algorithms for your business needs. The book starts by helping you develop your analytical thinking to create a problem statement using business inputs and domain research. You will then learn different evaluation metrics that compare various algorithms, and later progress to using these metrics to select the best algorithm for your problem. After finalizing the algorithm you want to use, you will study the hyperparameter optimization technique to fine-tune your set of optimal parameters. The book demonstrates how you can add different regularization terms to avoid overfitting your model. By the end of this book, you will have gained the advanced skills you need for modeling a supervised machine learning algorithm that precisely fulfills your business needs.

Who is this book for?

This book is specially designed for beginner and intermediate-level data analysts, data scientists, and data engineers who want to explore different methods of supervised machine learning and its use cases. Some background in statistics, probability, calculus, linear algebra, and programming will help you thoroughly understand and follow the concepts covered in this book.

What you will learn

  • Develop analytical thinking to precisely identify a business problem
  • Wrangle data with dplyr, tidyr, and reshape2
  • Visualize data with ggplot2
  • Validate your supervised machine learning model using k-fold
  • Optimize hyperparameters with grid and random search, and Bayesian optimization
  • Deploy your model on Amazon Web Services (AWS) Lambda with plumber
  • Improve your model's performance with feature selection and dimensionality reduction

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : May 31, 2019
Length: 502 pages
Edition : 1st
Language : English
ISBN-13 : 9781838556334
Category :
Languages :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : May 31, 2019
Length: 502 pages
Edition : 1st
Language : English
ISBN-13 : 9781838556334
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 147.97
Applied Supervised Learning with R
$48.99
Machine Learning with R
$59.99
Practical Machine Learning with R
$38.99
Total $ 147.97 Stars icon

Table of Contents

9 Chapters
R for Advanced Analytics Chevron down icon Chevron up icon
Exploratory Analysis of Data Chevron down icon Chevron up icon
Introduction to Supervised Learning Chevron down icon Chevron up icon
Regression Chevron down icon Chevron up icon
Classification Chevron down icon Chevron up icon
Feature Selection and Dimensionality Reduction Chevron down icon Chevron up icon
Model Improvements Chevron down icon Chevron up icon
Model Deployment Chevron down icon Chevron up icon
Capstone Project - Based on Research Papers Chevron down icon Chevron up icon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.