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
Conferences
Free Learning
Arrow right icon
Practical Machine Learning with R
Practical Machine Learning with R

Practical Machine Learning with R: Define, build, and evaluate machine learning models for real-world applications

Arrow left icon
Profile Icon Jeyaraman Profile Icon Wambugu Profile Icon Olsen
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (1 Ratings)
Paperback Aug 2019 416 pages 1st Edition
eBook
€8.99 €23.99
Paperback
€29.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Jeyaraman Profile Icon Wambugu Profile Icon Olsen
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (1 Ratings)
Paperback Aug 2019 416 pages 1st Edition
eBook
€8.99 €23.99
Paperback
€29.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€8.99 €23.99
Paperback
€29.99
Subscription
Free Trial
Renews at €18.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

Practical Machine Learning with R

Data Cleaning and Pre-processing

Learning Objectives

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

  • Perform the sort, rank, filter, subset, normalize, scale, and join operations in an R data frame.
  • Identify and handle outliers, missing values, and duplicates gracefully using the MICE and rpart packages.
  • Perform undersampling and oversampling on a dataset.
  • Apply the concepts of ROSE and SMOTE to handle unbalanced data.

This chapter covers the important concepts of handling data and making the data ready for analysis.

Introduction

Data cleaning and preparation takes about 70% of the effort in the entire process of a machine learning project. This step is essential because the quality of the data determines the accuracy of the prediction model. A clean dataset should contain good samples of the scenarios that we want to predict, and this will give us good prediction results. Also, the data should be balanced, which means that every category we want to predict should have similar number of samples. For example, if we want to predict whether it will rain or not on any particular day, and if the sample data size is 100, the data could contain 40 samples for It will rain and 60 samples for It will not rain today, or vice versa. However, if the ratio is 20:80 or 30:70, it is an unbalanced dataset, and this will not yield good results for the minority class.

In the following section, we will look at the essential operations performed on data frames in R. These operations will help us to manipulate and analyze...

Advanced Operations on Data Frames

In the previous chapter, we performed a number of operations on data frames, including rbind(). There are many more operations that can be performed on data frames, which are very useful while preparing the data for the model. The following exercises will describe these operations in detail and illustrate them through their corresponding implementation in R:

  • The order function: The order function is used to sort a data frame. We can specify ascending or descending order using the "-" symbol.
  • The sort function: The sort function can also be used to sort the data. The order can be specified as "decreasing=TRUE" or "decreasing"="FALSE".
  • The rank function: The rank function is used to rank the values in the data in a numerical manner.

Sorting, ordering, and ranking are operations that act as techniques to identify outliers. Outliers are values that are either too big or too small and do not fit in the value...

Identifying the Input and Output Variables

For any dataset, we should identify the input variables and the output variables. For the iris dataset, the input variables are the following:

  1. SepalLength
  2. SepalWidth
  3. PetalLength
  4. PetalWidth

The output variable, or the field to be predicted, is Species.

Identifying the Category of Prediction

Based on the category of prediction, we will perform different pre-processing steps. The category of prediction could be any of these:

  • Categorical Prediction: In this type of prediction, the output to be predicted will have class values such as yes, no, or given categories.
  • Numeric Prediction: In a numeric prediction, the output that will be predicted is a numeric value, such as predicting the cost of a house.

Handling Missing Values, Duplicates, and Outliers

In any dataset, we might have missing values, duplicate values, or outliers. We need to ensure that these are handled appropriately so that the data used by the model is clean.

Handling Missing Values

Missing values in a data frame can affect the model during the training process. Therefore, they need to be identified and handled during the pre-processing stage. They are represented as NA in a data frame. Using the example that follows, we will see how to identify a missing value in a dataset.

Using the is.na(), complete.cases(), and md.pattern() functions, we will identify the missing values.

The is.na() function, as the name suggests, returns TRUE for those elements marked NA or, for numeric or complex vectors, NaN (Not a Number) , and FALSE. The complete.cases() function returns TRUE if the value is missing and md.pattern() gives a summary of the missing values.

Exercise 12: Identifying the Missing Values

In the following example, we are adding...

Handling Outliers

Any datapoint with a value that is very different from the other data points is an outlier. Outliers can affect the training process negatively and therefore they need to be handled gracefully. In the following section, we will illustrate via examples both the process of detecting an outlier and the techniques used to handle them.

Exercise 16: Identifying Outlier Values

The outlier package can detect the outlier values. Using the opposite=TRUE parameter will fetch the outliers from the other side of dataset. The outlier values can be verified using a boxplot.

  1. Attach the outlier package:

    library(outliers)

  2. Detect outliers:

    #Detect outliers

    outlier(PimaIndiansDiabetes[,1:4])

    The output is as follows:

    pregnant  glucose pressure  triceps

          17        0        0       99

    Detect outliers from the other end:

    #This...

Summary

In this chapter, we learned how to perform several operations on a data frame, including scaling, standardizing, and normalizing. Also, we covered the sorting, ranking, and joining operations with their implementations in R. We discussed the need for pre-processing of the data; and identified and handled outliers, missing values, and duplicate values.

Next, we moved on to the sampling of data. It is important for the data to contain a reasonable sample of each class that is to be predicted. If the data is imbalanced, it can affect our predictions in a negative manner. Therefore, we can use either the undersampling, oversampling, ROSE, or SMOTE techniques imbalanced to ensure that the dataset is representative of all the classes that we want to predict. This can be done using the MICE, rpart, ROSE, and caret packages.

In the next chapter, we will cover feature engineering in detail, where we will focus on extracting features to create models.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Gain a comprehensive overview of different machine learning techniques
  • Explore various methods for selecting a particular algorithm
  • Implement a machine learning project from problem definition through to the final model

Description

With huge amounts of data being generated every moment, businesses need applications that apply complex mathematical calculations to data repeatedly and at speed. With machine learning techniques and R, you can easily develop these kinds of applications in an efficient way. Practical Machine Learning with R begins by helping you grasp the basics of machine learning methods, while also highlighting how and why they work. You will understand how to get these algorithms to work in practice, rather than focusing on mathematical derivations. As you progress from one chapter to another, you will gain hands-on experience of building a machine learning solution in R. Next, using R packages such as rpart, random forest, and multiple imputation by chained equations (MICE), you will learn to implement algorithms including neural net classifier, decision trees, and linear and non-linear regression. As you progress through the book, you’ll delve into various machine learning techniques for both supervised and unsupervised learning approaches. In addition to this, you’ll gain insights into partitioning the datasets and mechanisms to evaluate the results from each model and be able to compare them. By the end of this book, you will have gained expertise in solving your business problems, starting by forming a good problem statement, selecting the most appropriate model to solve your problem, and then ensuring that you do not overtrain it.

Who is this book for?

If you are a data analyst, data scientist, or a business analyst who wants to understand the process of machine learning and apply it to a real dataset using R, this book is just what you need. Data scientists who use Python and want to implement their machine learning solutions using R will also find this book very useful. The book will also enable novice programmers to start their journey in data science. Basic knowledge of any programming language is all you need to get started.

What you will learn

  • Define a problem that can be solved by training a machine learning model
  • Obtain, verify and clean data before transforming it into the correct format for use
  • Perform exploratory analysis and extract features from data
  • Build models for neural net, linear and non-linear regression, classification, and clustering
  • Evaluate the performance of a model with the right metrics
  • Implement a classification problem using the neural net package
  • Employ a decision tree using the random forest library

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Aug 30, 2019
Length: 416 pages
Edition : 1st
Language : English
ISBN-13 : 9781838550134
Category :
Languages :
Tools :

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 : Aug 30, 2019
Length: 416 pages
Edition : 1st
Language : English
ISBN-13 : 9781838550134
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.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
€189.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
€264.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 111.97
Practical Machine Learning with R
€29.99
Machine Learning with R
€44.99
Applied Supervised Learning with R
€36.99
Total 111.97 Stars icon
Banner background image

Table of Contents

6 Chapters
An Introduction to Machine Learning Chevron down icon Chevron up icon
Data Cleaning and Pre-processing Chevron down icon Chevron up icon
Feature Engineering Chevron down icon Chevron up icon
Introduction to neuralnet and Evaluation Methods Chevron down icon Chevron up icon
Linear and Logistic Regression Models Chevron down icon Chevron up icon
Unsupervised Learning Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Full star icon 5
(1 Ratings)
5 star 100%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
floren25 Jun 22, 2021
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Los ejercicios y actividades propuestos en este libro son esenciales para el aprendizaje efectivo de Machine Learning. Los autores incluyen en el texto soluciones detalladas de unos y otras, de modo que puedes contrastar lo que has hecho con las respuestas correctas.Incluyen capítulos sobre limpieza y preprocesamiento de datos (la parte más ardua y costosa en tiempo de un análisis de aprendizaje automático), el cálculo mediante diversos métodos de la importancia relativa de las variables dentro de una base de datos, las redes neuronales artificiales y las diversas métricas para calibrar su idoneidad en modelos de clasificación (exactitud, precisión, sensibilidad, puntuación F1) y en modelos de regresión (coeficiente de determinación, raíz cuadrada del error cuadrático medio, error medio absoluto, entre otros).El grueso del libro está consagrado al aprendizaje supervisado. Sólo en el último capítulo, el 6º, se introduce el aprendizaje no supervisado, con especial atención a la técnica de k-means clustering.Hay que advertir, eso sí, que los autores apenas se detienen a explicar cómo se escribe código en R ni tampoco aclaran la mayoría de los conceptos estadísticos que emplean. Todo esto lo dan por sabido en el que leyere. De modo que este libro, con ser excelente y muy didáctico, no es para primerizos en el área.
Amazon Verified review Amazon
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.