<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="http://www.r-bloggers.com/how-to-use-data-analysis-for-machine-learning-example-part-1/"></div></div><div><a data-url="http://www.r-bloggers.com/how-to-use-data-analysis-for-machine-learning-example-part-1/" data-counturl="http://www.r-bloggers.com/how-to-use-data-analysis-for-machine-learning-example-part-1/" data-count="horizontal" data-text="How to use data analysis for machine learning (example, part 1)" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://www.sharpsightlabs.com/data-analysis-machine-learning-example-part1/"> r-bloggers – SHARP SIGHT LABS</a></strong>, and kindly contributed to <a rel="nofollow" href="http://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>In my last article, I stated that for practitioners (as opposed to theorists), <a href="http://www.sharpsightlabs.com/machine-learning-prerequisite-isnt-math/">the real prerequisite for machine learning is data analysis, not math</a>.</p>
<p>One of the main reasons for making this statement, is that data scientists spend an inordinate amount of time on data analysis. The traditional statement is that data scientists “spend 80% of their time on data preparation.” While I think that this statement is essentially correct, a more precise statement is that you’ll spend 80% of your time on getting data, cleaning data, aggregating data, reshaping data, and exploring data using exploratory data analysis and data visualization. (From this point forward, I’ll use the term “data analysis” as a shorthand for <i>getting data, reshaping it, exploring it, and visualizing it</i>.)</p>
<p>And ultimately, the importance of data analysis applies not only to data science generally, but machine learning specifically. </p>
<p>The fact is, if you want to build a machine learning model, you’ll spend huge amounts of time just doing data analysis as a <i>precursor</i> to that process. </p>
<p>Moreover, you’ll use data analysis to explore <i>the results</i> of your model after you’ve applied an ML algorithm. </p>
<p>Additionally, in industry, you’ll also need to rely heavily on data visualization techniques to <i>present</i> the results after you’ve finalized them. This is one of the practical details of <i>working</i> as a data scientist that many courses and teachers never tell you about. Creating presentations to communicate your results will take large amounts of your time. And to create these presentations, you should rely heavily data visualization to communicate the model results <i>visually</i>.</p>
<p><img sizes="(max-width: 600px) 100vw, 600px" srcset="http://i0.wp.com/www.sharpsightlabs.com/wp-content/uploads/2016/05/1_data-analysis-for-ML_how-we-use-dataAnalysis_2016-05-16-600x186.png?resize=456%2C141 600w, http://www.sharpsightlabs.com/wp-content/uploads/2016/05/1_data-analysis-for-ML_how-we-use-dataAnalysis_2016-05-16.png 623w" alt="1_data-analysis-for-ML_how-we-use-dataAnalysis_2016-05-16" class="wp-image-2607" src="http://i0.wp.com/www.sharpsightlabs.com/wp-content/uploads/2016/05/1_data-analysis-for-ML_how-we-use-dataAnalysis_2016-05-16-600x186.png?resize=456%2C141" data-recalc-dims="1"></p>
<p>Data analysis and data visualization are critical at almost every part of the machine learning workflow. </p>
<p>So, to get started with ML (and to eventually master it) you need to be able to <a href="http://machinelearningmastery.com/descriptive-statistics-examples-with-r/">apply visualization and analysis</a>.</p>
<p>In this post, I’ll show you some of the basic data analysis and visualization techniques you’ll need to know to build a machine learning model. </p>
<h3>We’ll work on a toy problem, for simplicity and clarity</h3>
<p>One note before we get started: the problem that we’ll work through is just linear regression and we’ll be using an easy-to-use, off-the-shelf dataset. It’s a “toy problem,” which is intentional. Whenever you try to learn a new skill, it is extremely helpful to <i>isolate different details</i> of that skill. </p>
<p>The skill that I really want you to focus on here is data visualization (as it applies to machine learning).</p>
<p>We’ll also be performing a little bit of data manipulation, but it will be in service of analyzing and visualizing the data. We won’t be doing any data manipulation to “clean” the data.</p>
<p>So just keep that in mind. We’re working on a very simplified problem. I’m removing or limiting several other parts of the ML workflow so we can strictly focus on preliminary visualization and analysis for machine learning.</p>
<h2>Step 1: get the data</h2>
<p>The first step almost of any analysis or model building effort is getting the data. </p>
<p>For this particular analysis, we’ll use a relatively “off the shelf” dataset that’s available in R within the MASS package.</p>
<pre class="wp-code-highlight">
data(Boston, package = &quot;MASS&quot;)
</pre>
<p>The  dataset contains data on median house price for houses in the Boston area. The variable that we’ll try to predict is the  variable (median house price). The dataset has roughly a dozen other predictors that we’ll be investigating and using in our model. </p>
<h3>This is a simplified “toy example” data doesn’t require much cleaning</h3>
<p>As I already mentioned, the example we’ll be working through is a bit of a “toy” example, and as such, we’re working with a dataset that’s relatively “easy to use.” What I mean is that I’ve chosen this dataset because it’s easy to obtain and it doesn’t require much data cleaning.</p>
<p>However, keep in mind that in a typical business or industry setting, you’ll probably need to get your data from a database using SQL or possibly from a spreadsheet or other file.</p>
<p>Moreover, it’s very common for data to be “messy.” The data may have lots of missing values; variable names and class names that need to be changed; or other details that need to be altered.</p>
<p>Again, I’m intentionally leaving “data cleaning” out of this blog post for the sake of simplicity.</p>
<p>Just keep in mind that in many cases, you’ll have some data cleaning to do.</p>
<h2>Step 2: basic data exploration</h2>
<p>After getting the dataset, the next step in the model building workflow is almost always data visualization. Specifically, we’ll perform exploratory data analysis on the data to accomplish several tasks:</p>
<p>1. View data distributions<br>
2. Identify skewed predictors<br>
3. Identify outliers</p>
<h3>Visualize data distributions</h3>
<p>Let’s begin our data exploration by visualizing the data distributions of our variables.</p>
<p>We can start by visualizing the distribution of our target variable, .</p>
<p>To do this, we’ll first use a basic histogram. </p>
<p>I strongly believe that the histogram is one of the “core visualization techniques” that every data scientists should master. If you want to be a great data scientist, and if you ultimately want to build machine learning models, then mastering the histogram is one of your “first steps.” </p>
<p>By “master”, I mean that you should be able to write this code “with your eyes closed.” A good data scientist should be able to write the code to create a histogram (or scatterplot, or line chart ….) from scratch, without any reference material and without “copying and pasting.” You should be able to write it from memory almost as fast as you can type. </p>
<p>One of the reasons that I believe the histogram is so important is because we use it frequently in this sort of exploratory data analysis. When we’re performing an analysis or building a model, it is extremely common to examine the distribution of a variable. Because it’s so common to do this, you should know this technique cold.</p>
<p>Here’s the code to create a histogram of our target variable .</p>
<pre class="wp-code-highlight">
############################
# VISUALIZE TARGET VARIABLE
############################

require(ggplot2)

#~~~~~~~~~~~
# histogram
#~~~~~~~~~~~

ggplot(data = Boston, aes(x = medv)) +
  geom_histogram()
</pre>
<p><img alt="2_data-analysis-for-ML_histogram-medv_2016-05-16" class="wp-image-2608" src="http://i1.wp.com/www.sharpsightlabs.com/wp-content/uploads/2016/05/2_data-analysis-for-ML_histogram-medv_2016-05-16.png?resize=437%2C359" data-recalc-dims="1"></p>
<p>If you don’t really understand how this code works, I’d highly recommend that you read my <a href="http://www.sharpsightlabs.com/histogram-in-r-basic/">blog post about how to create a histogram with ggplot2</a>. That post explains how the histogram code works, step by step. </p>
<p>Let’s also create a density plot . </p>
<p>Here’s the exact code to create a density plot .</p>
<pre class="wp-code-highlight">
#~~~~~~~~~~~~~~
# density plot
#~~~~~~~~~~~~~~

ggplot(data = Boston, aes(x = medv)) +
  stat_density()
</pre>
<p>The density plot is essentially a variation of the histogram. The code to create a density plot is essentially identical to the code for a histogram, except that the second line is changed from  to . Speaking in terms of ggplot2 syntax, we’re replacing the histogram geom with a statistical transformation.</p>
<p><img alt="3_data-analysis-for-ML_density-medv_2016-05-16" class="wp-image-2609" src="http://i2.wp.com/www.sharpsightlabs.com/wp-content/uploads/2016/05/3_data-analysis-for-ML_density-medv_2016-05-16.png?resize=456%2C411" data-recalc-dims="1"></p>
<p>If you’ve been working with data visualization for a while, you might want to learn a little bit about the differences between histograms and density plots, and how we use them. This is more of an intermediate data visualization topic, but it’s relevant to this blog post on ‘data visualization for machine learning’, so I’ll mention it.</p>
<p>Between histograms and density plots, <a href="http://andrewgelman.com/2009/10/23/variations_on_t/">some people strongly prefer histograms</a>. The primary reason for this is that histograms tend to “<a href="http://andrewgelman.com/2009/10/23/variations_on_t/">provide better information on the exact location of data</a>” (which is good for detecting outliers). This is true in particular when you use a relatively larger number of histogram bins; a histogram with a sufficiently large number of bins can show you peaks and unusual data details a little better, because it doesn’t smooth that information away. (Density plots and histograms with a small number of bins can smooth that information out too much.) So, when we’re visualizing a single variable, the histogram might be the better option.</p>
<p>However, when we’re visualizing multiple variables at a time, density plots are easier to work with. If you attempt to <a href="http://www.sharpsightlabs.com/small-multiples-ggplot/">plot several histograms at the same time by using a small multiple chart</a>, it can be very difficult to select a single binwidth that properly displays all of your variables. Because of this, density plots are easier to work with when you’re visualizing multiple variables in a small multiple chart. Density plots show the general shape of the data and we don’t have to worry about choosing the number of bins.</p>
<p>Ok, so having plotted the distribution of our target variable, let’s examine the plots. We can immediately see a few important details:</p>
<p>1. It’s not perfectly normal. </p>
<p>This is one of the things we’re looking for when we visualize our data (particularly for linear regression). I’ll save a complete explanation of why we test for normality in linear regression and machine learning, but in brief, we are examining this because many machine learning techniques require normally distributed variables. </p>
<p>2. It appears that there may be a few minor outliers in the far right tail of the distribution. For the sake of simplicity, we’re not going to deal with those outliers here; we’ll be able to build a model (imperfect though it might be) without worrying about those outliers right now. </p>
<p>Keep in mind, however, that you’ll be looking for them when you plot your data, and in some cases, they may be problematic enough to warrant some action.</p>
<p>Now that we’ve examined our target variable, let’s look at the distributions of <i>all</i> of the variables in our dataset. </p>
<p>We’re going to visualize all of our predictors <i>in a single chart</i>, like this: </p>
<p><img alt="4_data-analysis-for-ML_variable-small-multiple_2016-05-16" class="wp-image-2610" src="http://i0.wp.com/www.sharpsightlabs.com/wp-content/uploads/2016/05/4_data-analysis-for-ML_variable-small-multiple_2016-05-16.png?resize=456%2C408" data-recalc-dims="1"></p>
<p>This is <a href="http://www.sharpsightlabs.com/small-multiples-ggplot/">known as a small multiple chart</a> (sometimes also called a “trellis chart”). Basically, the small multiple chart allows you to plot many charts in a grid format, side by side. It allows you to <a href="http://www.juiceanalytics.com/writing/better-know-visualization-small-multiples">use the same basic graphic or chart to display different slices of a data set</a>. In this case, we’ll use the small multiple to visualize different variables.</p>
<p>You might be tempted to visualize each predictor individually – one chart at a time – but that can get cumbersome and tedious very quickly. When you’re working with more than a couple of variables, the small multiple will save you lots of time. This is particularly true if you work with datasets with dozens, even hundreds of variables.</p>
<p>Although the small multiple is perfect for a task like this, we’ll have to do some minor data wrangling to use it.</p>
<h3>Reshape the data for the small multiple chart</h3>
<p>To use the small multiple design to visualize our variables, we’ll have to manipulate our data into shape. </p>
<p> Before we reshape the data, let’s take a look at the data as it currently exists:</p>
<pre class="wp-code-highlight">
head(Boston)
</pre>
<p><img alt="5_data-analysis-for-ML_head-boston-dataset_2016-05-16" class="wp-image-2611" src="http://i0.wp.com/www.sharpsightlabs.com/wp-content/uploads/2016/05/5_data-analysis-for-ML_head-boston-dataset_2016-05-16.png?resize=456%2C100" data-recalc-dims="1"></p>
<p>Notice that the variables are currently located as <i>columns</i> of the data frame. For example, the  variable is the first column. This is how data is commonly formatted in a data frame; typical data frames have variables as columns, and data observations as rows. This format is commonly called “wide-format” data.</p>
<p>However, to create a “small multiple” to plot all of our variables, we need to reshape our data so that the variables are along the rows; we need to reshape our data into “long-format.’</p>
<p>To do this, we’re going to use the  function from the  package. This function will change the shape of the data from wide-format to long-format.</p>
<pre class="wp-code-highlight">
require(ggplot2)
require(reshape2)
melt.boston &lt;- melt(Boston)
head(melt.boston)
</pre>
<p><img alt="6_data-analysis-for-ML_melt-boston-dataset_2016-05-16" class="wp-image-2612" src="http://i1.wp.com/www.sharpsightlabs.com/wp-content/uploads/2016/05/6_data-analysis-for-ML_melt-boston-dataset_2016-05-16.png?resize=122%2C126" data-recalc-dims="1"></p>
<p>After using , notice that the  variable (which had been a column) is now dispersed along the rows of our reshaped dataset, . In fact, if you examine the whole dataset, all of our dataset features are now along rows.</p>
<p>Now that we’ve melted our data into long-format, we’re going to use ggplot2 to create a small multiple chart. Specifically, we’ll <a href="http://www.sharpsightlabs.com/small-multiples-ggplot/"> use  to implement the small-multiple design</a>.</p>
<pre class="wp-code-highlight">
ggplot(data = melt.boston, aes(x = value)) +
  stat_density() +
  facet_wrap(~variable, scales = &quot;free&quot;)
</pre>
<p><img alt="4_data-analysis-for-ML_variable-small-multiple_2016-05-16" class="wp-image-2610" src="http://i0.wp.com/www.sharpsightlabs.com/wp-content/uploads/2016/05/4_data-analysis-for-ML_variable-small-multiple_2016-05-16.png?resize=456%2C408" data-recalc-dims="1"></p>
<p>So now that we’ve visualized the distributions of all of our variables, what are we looking for?</p>
<p>We’re looking primarily for a few things:</p>
<p>1. Outliers<br>
2. Skewness<br>
3. Other deviations from normality</p>
<p>Let’s examine skewness first (simply because that seems to be one of the primary issues with these features).</p>
<p>Just to refresh your memory, skewness is a <a href="https://en.wikipedia.org/wiki/Skewness">measure of asymmetry of a data distribution</a>. </p>
<p>You can immediately see that several of the <a href="https://en.wikipedia.org/wiki/Skewness">variables are highly skewed </a>. </p>
<p>In particular, , , , , and  are highly skewed. Several of the others appear to have moderate skewness.</p>
<p>We’ll quickly confirm this by calculating the skewness:</p>
<pre class="wp-code-highlight">
#~~~~~~~~~~~~~~~~~~~~
# calculate skewness
#~~~~~~~~~~~~~~~~~~~~

require(e1071)
sapply(Boston, skewness)
</pre>
<p><img sizes="(max-width: 600px) 100vw, 600px" srcset="http://i2.wp.com/www.sharpsightlabs.com/wp-content/uploads/2016/05/7_data-analysis-for-ML_sapply-skewness-boston_2016-05-16-600x57.png?resize=456%2C43 600w, http://www.sharpsightlabs.com/wp-content/uploads/2016/05/7_data-analysis-for-ML_sapply-skewness-boston_2016-05-16.png 719w" alt="7_data-analysis-for-ML_sapply-skewness-boston_2016-05-16" class="wp-image-2613" src="http://i2.wp.com/www.sharpsightlabs.com/wp-content/uploads/2016/05/7_data-analysis-for-ML_sapply-skewness-boston_2016-05-16-600x57.png?resize=456%2C43" data-recalc-dims="1"></p>
<p>To be clear, skewness can be a bit of a slippery concept, but note that a skewness of zero indicates a symmetrical distribution. Ideally, we’re looking for variables with a skewness of zero.</p>
<p>Also, a very rough rule of thumb is <a href="https://amzn.com/dp/B008TVLLIM">if the absolute value of skewness is above 1, then the variable has high skewness</a>.</p>
<p>Looking at these numbers, a few of the variables have relatively low skewness, including , , and  (although  is much more symmetrical).</p>
<h3>Note: how we (normally) use this info</h3>
<p>Part of the task of data exploration for ML is <i>knowing what to do</i> with the information uncovered in the data exploration process. That is, once you’ve identified potential problems and salient characteristics of your data, you need to be able to transform your data in ways that will make the machine learning algorithms work better. As I said previously, “data transformation” is a separate skill, and because we’re focusing on the pure “data exploration” process in this post, we won’t discussing data transformations. (Transformations are a big topic.)</p>
<p>Be aware, however, that in a common ML workflow, your learnings from EDA will serve as an input to the “data transformation” step of your workflow. </p>
<h2>Recap</h2>
<p>Let’s recap what we just did:</p>
<p>1. Plotted a histogram of our target variable using ggplot2<br>
2. Reshaped our dataset using melt()<br>
3. Plotted the variables using the small multiple design<br>
4. Examined our variables for skewness and outliers</p>
<p>To be honest, this was actually an abbreviated list of things to do. We could also have looked at correlation, among other things. </p>
<p>This is more than enough to get you started though. </p>
<h3>Tools that we leveraged.</h3>
<p>By now, you should have some indication of what skills you need to know to get started with practical machine learning in R:</p>
<p>1. Learn ggplot2<br>
– master basic techniques like the histogram and scatterplot<br>
– learn how to facet your data in ggplot2 to perform multivariate data exploration</p>
<p>2. Learn basic data manipulation. I’ll suggest dplyr (which we didn’t really use here), and also reshape.</p>
<h2>Want to see part 2?</h2>
<p>In the next post, we’ll continue our use of data analysis in the ML workflow. </p>
<p>If you want to see part 2, sign up for the email list, and the next blog post will be delivered automatically to your inbox as soon as it’s published.</p>
<p>The post <a target="_blank" rel="nofollow" href="http://www.sharpsightlabs.com/data-analysis-machine-learning-example-part1/">How to use data analysis for machine learning (example, part 1)</a> appeared first on <a target="_blank" rel="nofollow" href="http://www.sharpsightlabs.com/">SHARP SIGHT LABS</a>.</p>
<p><div><div><div><div data-width="55" data-show-faces="false" data-send="true" data-layout="box_count" data-height="62" data-href="http://www.r-bloggers.com/how-to-use-data-analysis-for-machine-learning-example-part-1/"></div></div><div><a data-url="http://www.r-bloggers.com/how-to-use-data-analysis-for-machine-learning-example-part-1/" data-counturl="http://www.r-bloggers.com/how-to-use-data-analysis-for-machine-learning-example-part-1/" data-count="vertical" data-text="How to use data analysis for machine learning (example, part 1)" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://www.sharpsightlabs.com/data-analysis-machine-learning-example-part1/"> r-bloggers – SHARP SIGHT LABS</a></strong>.</div>
<hr>
<a rel="nofollow" href="http://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="http://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="http://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="http://www.r-bloggers.com/?s=tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="http://www.r-bloggers.com/?s=data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="http://www.r-bloggers.com/?s=Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="http://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="http://www.r-bloggers.com/?s=ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="http://www.r-bloggers.com/?s=boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="http://www.r-bloggers.com/?s=map">maps</a>, <a title="Animation in R" rel="nofollow" href="http://www.r-bloggers.com/?s=animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="http://www.r-bloggers.com/?s=RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="http://www.r-bloggers.com/?s=sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="http://www.r-bloggers.com/?s=LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="http://www.r-bloggers.com/?s=SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="http://www.r-bloggers.com/?s=eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="http://www.r-bloggers.com/?s=git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="http://www.r-bloggers.com/?s=hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="http://www.r-bloggers.com/?s=Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="http://www.r-bloggers.com/?s=regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="http://www.r-bloggers.com/?s=PCA">PCA</a>, <a title="Time series" rel="nofollow" href="http://www.r-bloggers.com/?s=time+series">time series</a>, <a title="finance trading" rel="nofollow" href="http://www.r-bloggers.com/?s=trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/5AJM5HjsUe8"></a></div>